This happens because the default property for vertical-align
is baseline
, and you don't specify it in your example. This means that the inline-block elements will align to their baseline:
The baseline of an 'inline-block' is the baseline of its last line box in the normal flow, unless it has either no in-flow line boxes or if its 'overflow' property has a computed value other than 'visible', in which case the baseline is the bottom margin edge.
In short, that means that if there is text in an inline-block element, then the element will align to the base of that text. If there is no text, it will align to the bottom margin. So inline-block elements with text in them get pushed down compared to those without.
This is corrected by setting a vertical-align
of top
, bottom
, or more preferably, middle
:
div {
display: inline-block;
height: 100px;
width: 100px;
vertical-align: middle;
}
<div style="background:grey;">first</div>
<div style="background:red;"></div>
One could float
the elements to the left
, though this works because float
takes the elements out of the flow context, and treats them as block elements. Applying float: left
essentially removes display: inline-block
; you cannot float
an inline-block element.
div {
display: inline-block;
height: 100px;
width: 100px;
float: left;
}
<div style="background:grey;">first</div>
<div style="background:red;"></div>
Gives the same effect as:
div {
height: 100px;
width: 100px;
float: left;
}
<div style="background:grey;">first</div>
<div style="background:red;"></div>