Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are these two identical inline divs misaligned when one has text and the other doesn't?

Tags:

html

css

So here are two identical divs:

HTML

<div id="left"></div>
<div id="right"></div>

CSS

#left, #right
{
    width: 100px;
    height: 40px;
    border: 1px solid gray;
    display: inline-block;
}

These render just fine, as two identical boxes side-by-side (fiddle: http://jsfiddle.net/URy59/).

inline divs

But with text in one div, and none in the other, they're misaligned! (fiddle: http://jsfiddle.net/URy59/1/)

This...

<div id="left"></div>
<div id="right">Right</div>

...results in:

misaligned divs

This behaviour is reproducible using <span> as well.

What causes this, and why? What's a good solution to this?

like image 717
SNag Avatar asked Dec 05 '22 07:12

SNag


2 Answers

The short answer: set the vertical-align property to top.

The longer answer: An inline element's default vertical alignment is baseline. When your divs have no content, they line up fine. However when you added the text, the browser then will move the div downward so that the text sits on the baseline:

enter image description here

By changing the alignment to top, you align the divs the way you need.

jsFiddle example

like image 182
j08691 Avatar answered Jan 02 '23 15:01

j08691


You need to vertically align your elements:

#left, #right {
    ...
    vertical-align: top;
}

JSFiddle demo.

like image 23
James Donnelly Avatar answered Jan 02 '23 15:01

James Donnelly