Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty div vs div with text having inline-block property

Tags:

html

css

Want to know the reason for this behavior.

CSS

div {
   display: inline-block;
   margin-right: 2px;
   width: 20px;
   background-color: red;
}

Empty div

<div style="height:20px;"></div>
<div style="height:40px;"></div>
<div style="height:60px;"></div>
<div style="height:80px;"></div>

behavior: element increases from bottom to top (height)

div with text

<div style="height:20px;">20</div>
<div style="height:40px;">30</div>
<div style="height:60px;">40</div>
<div style="height:80px;">50</div>

behavior: element increases from top to bottom (height)

see it in action: http://jsfiddle.net/8GGYm/

like image 687
kp singh Avatar asked Jul 21 '14 10:07

kp singh


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.

What is inline-block property?

“display: inline-block” Property: This property is used to display an element as an inline-level block container. The element itself is formatted as an inline element, but it can apply height and width values. It is placed as an inline element (on the same line as adjacent content).

Can a div be empty?

Every Website Uses Empty Divs. If you wanna use it then you can. There are no limitations.


2 Answers

Basically it got to do with the way that vertical-align: is calculated. So if you put vertical-aling:bottom; attribute in the css then you will notice it will be the same with and without text.

you can read the this for more details.

When the div has no content, padding is not drawn in the box (i.e. when when 0, if there is content, the browser calculates where the padding would be). so there is a little difference in calculating with and without text.

Hope this is helpfull.

like image 66
Faran Khan Avatar answered Sep 23 '22 16:09

Faran Khan


please see here: http://jsfiddle.net/dd24z/. By default text is vertical-align: top, but you can change that behavior:

div {
    display: inline-block;
    margin-right: 2px;
    width: 20px;
    background-color: red;
    vertical-align: bottom;
}

http://www.w3.org/TR/2008/REC-CSS2-20080411/visudet.html#line-height

'vertical-align': baseline Align the baseline of the box with the baseline of the parent box. If the box doesn't have a baseline, align the bottom of the box with the parent's baseline.

like image 21
sylwester Avatar answered Sep 22 '22 16:09

sylwester