Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a container of inline-block divs become too high?

Tags:

html

css

I have a container div and 5 child div's with

{display: inline-block}

so they appear next to each other. Each of the child div's have a height of 20px, but the container grows to a height of 24px. Why does this happen?

Fiddle: http://jsfiddle.net/VHkNx/

like image 940
Ben Davis Avatar asked Sep 25 '13 11:09

Ben Davis


People also ask

Can we change the height and width of inline-block?

Inline element properties: The height of an inline element is the height of the content. The width of an inline element is the width of the content. The height and width of an inline element cannot be set in CSS. You cannot set the height and width of block-level elements in CSS.

What's one advantage to using inline-block over inline display?

Compared to display: inline , the major difference is that inline-block allows to set a width and height on the element. Also, with display: inline , top and bottom margins & paddings are not respected, and with display: inline-block they are.

How do inline-block elements add up to 100 width?

To do this, you simply need to add display: flex to the parent container and flex-grow: 1 to the divs (as opposed to defining a width). With the flexbox styles applied, we can have three inline divs of equal width – just as we can with the inline-block solutions.

Do inline-block elements have width and height?

Compared to display: inline , the major difference is that display: inline-block allows to set a width and height on the element. Also, with display: inline-block , the top and bottom margins/paddings are respected, but with display: inline they are not.


3 Answers

Inline block elements still take care of the line-height/font-size. So adding this:

line-height: 0;

to #container will fix it.

Demo

Try before buy

like image 154
insertusernamehere Avatar answered Nov 07 '22 08:11

insertusernamehere


Once you're using the inline-block display, your elements behaves similarly to words and letters. Whitespaces and line heights are rendered as well and it might cause some unexpected results.

One way of solving this is to give the container font-size: 0 setting (of course you can still give the child elements themselves their own font size).

jsFiddle Demo


  • P.S - line-height: 0 will also work.
like image 32
Itay Avatar answered Nov 07 '22 08:11

Itay


One simple way of fixing this is to add vertical-align: top to the child elements:

.thing {
    vertical-align: top;
    display: inline-block;
    background-color: Red;
    height: 20px;
    width: 18%;
    margin-left: 1.25%;
    margin-right: 1.25%;
}

This way, you don't need to adjust line heights or font sizes.

As noted earlier, a similar layout can be realized using floats. Both approaches are valid. See demo at: http://jsfiddle.net/audetwebdesign/74Y2V/

like image 35
Marc Audet Avatar answered Nov 07 '22 09:11

Marc Audet