Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inline-block element nested in another inline-block element has an offsetTop

Tags:

html

css

I'm new learning HTML and now I have some code like

<div id="container" style="height:300px;width:500px;font-size:0">
    <div id="leftBox" style="display: inline-block; background: pink; width: 50%; height: 100%;">
        <div id="wrapper" style="height:10%;">
            <div style="display: inline-block; background: red; width: 50%; height: 100%;"></div>
            <div style="display: inline-block; background: blue; width: 50%; height: 100%;"></div>
        </div>
    </div>
    <div id="rightBox" style="display: inline-block; background: green; width: 50%; height: 100%;"></div>
</div>

(And I posted it on http://jsfiddle.net/Simon_Chan/Z3WyA/ )

You can see the leftBox has a big offsetTop, but if there is no wrapper or wrapper's height is 100% or there is no rightBox or there is no elements in wrapper, in all these conditions leftBox has no offsetTop.

Why do it? And how to remove it?

Thanks!

like image 576
yume_chan Avatar asked Apr 10 '13 21:04

yume_chan


2 Answers

To fix the problem you need to add vertical-align:top to #leftBox or #rightBox

The reason is that the default vertical-align value is baseline which

Aligns the baseline of the box with the baseline of the parent box

The baseline of the parent box is the bottom of the box.

Baseline is defined as

the line upon which most letters "sit" and below which descenders extend

All the cases you describe in the question result in the baseline being altered which aligns the elements as desired.

A good example of the baseline is the following code in which there are no elements in your wrapper <div> but very large font-size text instead. You can see how the bottom of the green <div> is aligned to the baseline of the parent (the red dotted border <div>) and how the pink <div>s text makes it move to where the text it sitting on the parent baseline.

<div style="height:300px;width:500px;font-size:0;border:1px dotted red">
    <div style="display: inline-block; background: pink; width: 50%; height: 100%;">
        <div style="height:100%;font-size:150px">foo</div>
    </div>
    <div style="display: inline-block; background: green; width: 50%; height: 100%;"></div>
</div>
like image 126
andyb Avatar answered Sep 27 '22 21:09

andyb


It does that because of the way the various boxes sit on the baseline. The simplest way to remove the problem is to vertically align them differently. e.g. use div {vertical-align:top }

To see how inline-block boxes sit on the baseline by default see http://jsfiddle.net/veCEf/. Note particularly how inline-block div boxes without any content have the bottom of their box sitting on the baseline, while once they have content, the bottom of their content sits on the baseline.

like image 20
Alohci Avatar answered Sep 27 '22 23:09

Alohci