使用line-height时,将块元素在顶部对齐 [英] align block elements on top when using line-height

查看:170
本文介绍了使用line-height时,将块元素在顶部对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果将line-height赋予 block元素(如h1),则会在每个文本行的上方和下方添加空格,这意味着该元素不会在同一顶部开始.如果我只想在每行下面留一个间距怎么办?我知道vertical-align仅适用于 inline-elements .

If I give a line-height to a block element like h1 it adds the space above and below the each text line, that means the element does not begin on the same top position. What if I just want a spacing below each line? I know that vertical-align does only work with inline-elements.

我还认识到,默认情况下,像p标记这样的块元素的文本不在行高"normal"的顶部.如果将背景色添加到元素,则该颜色在文本上方几像素处也是可见的.为什么?

I also recognized that a text of a block element like a p tag is not on top with line-height "normal", by default. If I add a background-color to the element, the colour is also visible a few pixels above the text. Why?

推荐答案

TLDR :使用position: relative和负的最高值进行伪造.

TLDR: Use position: relative and a negative top value to fake it.

说明:您是对的.行高总是添加在每个字符的上方和下方.因此,如果您的字体大小为12px,并且行高为18px,则每条线"的上方和下方分别为3px和3px.这3px的空格中的每一个都称为半前导".

Explanation: You're right. Line-height is always added above and below each character. So if your font-size is 12px and you have a line-height of 18px, you'll get 3px above and 3px below each "line". Each of those 3px spaces is called a "half-leading".

但是,您可以将position: relative与一个负的上限值一起使用,以使每行下面似乎只添加了空格.

However, you can use position: relative with a negative top value to make it seem like there is only space added beneath each line.

所以可以说,您希望每行之间有8px的空间,而不是上面示例中的6px(18px/12px = 6px = 3px在顶部+ 3px在底部).为此,请将行高从18px增加到20px,以使半前导4px,并在行与行之间总共留出8px的间距.然后添加position: relative; top: -2px,将行重新凸出到行高为18px的位置.

So lets say you wanted to have 8px of space between each line instead of just 6px from the example above (18px/12px = 6px = 3px on top + 3px on bottom) . To do this, increase the line-height from 18px to 20px to make the half-leading 4px and give a total of 8px of space between lines. Then add position: relative; top: -2px to bump the line back to same place it was when the line-height was 18px.

即使浏览器仍在每行上方和下方添加4px的空间,但负的垂直位置将使顶部多余的空间似乎被切断.

Even though the browser is still adding 4px of space above and below each line, the negative vertical positioning will make it seem like that extra top spacing was cut off.

这篇关于使用line-height时,将块元素在顶部对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆