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.
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?
Center Align Elements To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.
To place an item at the top or bottom of its cell, insert the "VALIGN=" attribute within the code for that cell. To vertically align an entire row (e.g., placing all data in that row at the tops of the cells), insert the "VALIGN=" attribute within the code for that row.
Inline elements or inline-block elements such as text, anchor, etc. can be aligned vertically with the help of CSS padding, CSS line-height, or CSS vertical-align property. Block-level elements such as div, p, etc.
According to the CSS Flexible Box Layout Module, you can declare the a element as a flex container (see figure) and use align-items to vertically align text along the cross axis (which is perpendicular to the main axis). All you need to do is: display: flex; align-items: center; See this fiddle.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With