Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

align block elements on top when using line-height

Tags:

css

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?

like image 933
m4mpfi Avatar asked Nov 03 '10 16:11

m4mpfi


People also ask

How do you align block elements?

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.

How do you align something to the top in HTML?

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.

How do you align inline elements?

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.

How do you vertically align text in block element?

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.


1 Answers

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.

like image 150
timmfin Avatar answered Sep 20 '22 12:09

timmfin