Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inline-block elements are line breaking for seemingly no reason?

I have some pretty basic HTML/CSS that isn't working as I expect. Basically I have my body setup to be 400px wide. I then have two divs inside of the body with explicit widths of 300px and 100px. Additionally, both of these divs are set to display: inline-block. For some reason, the 100px div breaks out of the body's content area and appears below it. I don't know why this is happening. If I set the width from 100px to 96px, it works. However, if I set it to 97px, 98px, 99px, or back to 100px, it doesn't work. I find this behavior very odd. Can someone explain what is going wrong?

Note that I am testing this on Chrome (Beta Channel). Code is below.

The CSS:

body {
    margin: 4px;
    width: 400px;
    height: 250px;
    border: 1px solid black;
}

.list-container {
    display: inline-block;
    width: 300px;
    height: 100%;
    background-color: red;
}

.button-container {
    display: inline-block;
    width: 100px;
    height: 100%;
    background-color: blue;
}

The HTML:

<body>

<div class="list-container">
</div>

<div class="button-container">
</div>

</body>
like image 926
void.pointer Avatar asked Dec 07 '22 21:12

void.pointer


1 Answers

It's because of the way white-space collapses in html.

If you remove the line-breaks from between the two div elements, everything's fine:

<div class="list-container">
</div><div class="button-container">
</div>

JS Fiddle demo.

You could, also, just comment-out the between divs:

<div class="list-container">
</div><!--

--><div class="button-container">
</div>

JS Fiddle demo.

Or even set the font-size to zero for the body element (but you'll have to redefine it for the child elements, obviously:

body {
    margin: 4px;
    width: 400px;
    height: 250px;
    border: 1px solid black;
    padding: 0;
    font-size: 0;
}

JS Fiddle demo.

like image 103
David Thomas Avatar answered Jan 11 '23 03:01

David Thomas