鉴于以下情况:
<div style="float: left; line-height: 24px;">
Would<br />
Be Nice<br />
If Aligned<br />
To the "top"<br />
</div>
观察 Chrome 中的文本与“行”的底部对齐(IE 似乎将文本居中)。
有没有一种方法,不用将每一行包装在 div(或 span)中,即可垂直对齐其“行”内的文本?
最佳答案
此方法的一些问题:
来自align block elements on top when using line-height :
Line-height is always added above and below each character. So if your
font-size
is 12px and you have aline-height
of 18px, you'll get 3px above and 3px below each "line". Each of those 3px spaces is called a "half-leading"
解决方案是相对定位每个元素,然后应用负边距,但我们不能在这里这样做,因为每一行都不是它自己的元素,如下所示:
Is there a way, without wrapping each line in a div (or span)
如果您确实不愿意修改标记,这里有一个 JavaScript/CSS 解决方法。当文本上方有“半行距”时,我们无法顶部对齐。相反,我们需要摆脱 line-height
顶部和底部的间距,并在底部创建我们自己的间距。我们如何知道每条线的底部在哪里?好吧,我们可以使用<br/>
元素,但我们 can't style a carriage return .
因此,我们将使用 javascript 来获取可以设置样式的内容,然后以这种方式添加一些间距:
JavaScript:
$('br').before('<div class="spacer"></div>');
CSS:
.spacer {
height: 24px;
display: inline-block;
}
Working Demo in JsFiddle
应该是这样的:
**注意:带有 inline-block
div,您必须将 line-height
的高度设置为您想要的高度并将 div 文本垂直对齐到 top
。您还可以使用 regular div with a negative margin-top
占用段落之间的额外空间。*
关于html - CSS 对齐 html 中的文本 "line",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20225734/