Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inline-block div with and without text not vertically aligned

Tags:

html

css

I have two divs side by side. Both have the same size and display: inline-block. The only difference between the two is, the first one has some text and the second one is blank.

HTML:

<div>1</div>
<div></div>

CSS:

div {
    display: inline-block;
    border: 1px solid black;
    width: 50px;
    height: 50px;
}

The first div is lower than the second one.

I am aware of all the possible fixes, like adding some text or a &nbsp; to the second div. Adding vertical-align: top fixes this as well, of course.

What I want to know is, can someone explain, why a blank div has a different alignment than a div with some text in it?

JSFiddle

like image 535
Olaf Dietsche Avatar asked Jun 19 '13 20:06

Olaf Dietsche


People also ask

Does text-align work on inline block?

Even though the property says “text” align, it affects all elements inside the block-level element that are either inline or inline-block elements. The property only affects the content inside the element to which it is applied, and not the element itself.

How do you align an inline block element?

To align things in the inline direction, use the properties which begin with justify- . Use justify-content to distribute space between grid tracks, and justify-items or justify-self to align items inside their grid area in the inline direction.

Is inline elements can be used for one line text only?

An inline element does not start on a new line. An inline element only takes up as much width as necessary. This is a <span> element inside a paragraph.


1 Answers

Inline-block boxes are, by default vertically aligned such that the baseline of the inline-block box aligns to the baseline of the line box in which it is rendered.

The baseline of an inline-block box with one line of text, is the baseline of that line. More generally, the baseline of an inline-block is the baseline of the last line of text that it contains. But that means that there is no baseline for an inline-block that contains no text.

In such a situation a fall back rule kicks in, and the bottom of the inline-block box is placed on the baseline of its line box.

like image 176
Alohci Avatar answered Oct 13 '22 00:10

Alohci