align block elements on top when using line-height
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
d开发者_JAVA技巧oes only work with inline-elements.
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: Use position: relative
and a negative top value to fake it.
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".
However, you can use position: relative
with a negative top value to make it seem like there is only space added beneath each line.
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.
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.
What if I just want a spacing below each line?
I don't really see how the accepted answer is any better than this, for most cases:
margin-bottom: .5em
The important thing is to use em
since is will be based on the current font size.
In addition note that if the text wraps to two lines and you're using line-height: 2
then you'll end up with a huge gap between the lines. Then you're almost certainly better off using margin-bottom
with a default line-height
.
精彩评论