Vertical align
You could apply vertical-align:top
to .word
.line {
background-color: red;
padding: 10px;
}
.word {
display: inline-block;
width: 100px;
height: 40px;
padding: 10px;
background-color: white;
vertical-align: top;
}
<div class="line">
<div class="word">hello</div>
<div class="word">there</div>
<div class="word"> </div>
<div class="word"></div>
</div>
Empty selector
Or add a rule for empty .word
divs, but this would still be malformed for divs with spaces in them. Could be helpful if you can't change the vertical-align
.line {
background-color: red;
padding: 10px;
}
.word {
display: inline-block;
width: 100px;
height: 40px;
padding: 10px;
background-color: white;
}
.word:empty:before {
content: "\0020";
display: inline-block;
}
<div class="line">
<div class="word">hello</div>
<div class="word">there</div>
<div class="word"> </div>
<div class="word"></div>
</div>
Why is this happening
Vertical alignment determines how 'inline' elements are positioned in relation to each other. by default it's set to baseline
Baseline will try to put 'most' of the text above the baseline and some of the dangling bits like the g
p
and q
and y
under the baseline.
That would make sense for text, the browser will attempt to do that for all text. Even text that's wrapped in divs and styled with paddings.
The entire empty div is put on the baseline.
Browser manufacturers just agreed that this is how it should be done.

If you look at it as if it where a text editor, It would make sense for small inline images, the default would be to push the entire line down based on the dimension of the image