【发布时间】:2020-10-28 10:19:23
【问题描述】:
在我的网站上,我正在按照以下 sn-p 中的示例精确对齐正文。
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 中的意思的示例。
注意:刚刚注意到第二个 sn-p 无法正确显示,除非您打开它进行编辑。如果你把它转移到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、视口单元、@987654330 @units 等),然后再浪费时间思考这个问题。 我知道有一些漂亮的 CSS 公式可用于流畅的排版,但这样的可能吗?
[ 编辑 ] 我躺在床上时想了更多。我不相信不计算“余数”是可能的。而且似乎没有任何方法可以仅用加法、减法、乘法和除法来计算“余数”。如果我错了,请纠正我。
【问题讨论】:
标签: javascript css math modulus typography