精确抵消文本的CSS公式

问题描述

在我的网站上,我正按照以下代码段中的示例对齐文本正文。

html,body {
  width: 100%;
  height: 100%;
  font-family: arial;
  font-size: 48px;
  text-transform: uppercase;
}

body {
  margin: 0;
  background: skyblue;
}

div {
  width: 200px;
  height: 100vh;
  padding-top: calc(100vh - (1.5rem * 1.35));
  box-sizing: border-box;
  border: solid red 1px;
}

span {
  line-height: 1.35;
  display: inline-block;
  border: solid black 1px;
}
<div><span>This</span>&nbsp;<span>is</span>&nbsp;<span>a</span><span>body</span><span>of</span>&nbsp;<span>text.</span></div>

但是,我希望将其进一步发展。例如,我希望能够将文本的顶部尽可能地靠近页面顶部的60vh,同时仍显示最后一行的一半。下面是我在JS中的意思的示例。

注意:只是注意到第二个代码段无法正确显示,除非您打开它进行编辑。如果将其转移到Codepen,它应该可以正常工作。

const
  div = document.querySelector('div'),span = document.querySelector('span'),lineHeight = parseFloat(getComputedStyle(span).lineHeight),target = innerHeight * 0.6,remainder = (innerHeight - target) / lineHeight % 1 * lineHeight

div.style.paddingTop = target + remainder - lineHeight / 2 + 'px'
html,body {
  width: 100%;
  height: 100%;
  font-family: arial;
  font-size: 48px;
  text-transform: uppercase;
}

body {
  margin: 0;
  background: skyblue;
}

div {
  width: 200px;
  height: 100vh;
  position: absolute;
  box-sizing: border-box;
  border: solid red 1px;
}

span {
  line-height: 1.5;
  display: inline-block;
  border: solid black 1px;
}
<div><span>This</span>&nbsp;<span>is</span>&nbsp;<span>a</span>&nbsp;<span>body</span>&nbsp;<span>of</span>&nbsp;<span>text.</span></div>

值得注意的是,我知道您显然可以使用calc,视口单位和rem找到“余数”,但是其余的却令人困惑,因为我不擅长数学并且还缺乏睡眠

因此,我希望那里的数学能力比我更好的人能够告诉我,没有预处理器的纯CSS解决方案是否可行(例如,仅使用calc,视口单位, rem个单位等)之前,我再花时间思考这个问题。 我知道流体排版有一些漂亮的CSS公式,但是这样的可能性吗?

[编辑]我躺在床上的时候想了更多。我不相信就不可能计算出“余数”。而且似乎没有任何方法可以仅通过加,减,乘和除来计算“余数”。如果我错了,请纠正我。

解决方法

目标是使DIV标签为文档高度的100%,然后使文本在DIV中稍微偏移一点?

我认为只需在DIV中添加另一个标签以抵消所有文本即可。您说要60vh。处理文字高度时也应使用行高。

html,body {
  width: 100%;
  height: 100%;
  font-family: arial;
  font-size: 48px;
  text-transform: uppercase;
}

body {
  margin: 0;
  background: skyblue;
}

div {
  width: 200px;
  height: 100vh;
  box-sizing: border-box;
  border: solid red 1px;

}

p
{   margin: 0;
    padding-top: 60vh;
  margin-top: -0.8em;
  line-height: 1.6em;
}

span {
  line-height: 1.35;
  display: inline-block;
  border: solid black 1px;
}
<html>
<body>
<div><p><span>This</span>&nbsp;<span>is</span>&nbsp;<span>a</span><span>body</span><span>of</span>&nbsp;<span>text.</span></p></div>
</body>
</html>

还是这样吗?

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...