Reputation: 26365
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>
Upvotes: 4
Views: 9266
Reputation: 10122
Another possibility with odd inline-block
behaviour in Chrome is if you have text-render: optimizeLegibility
set. I was struggling with inexplicable line-breaks in inline block elements in Chrome, and found that removing text-render: optimizeLegibility
fixed the problem.
I've had at least one other hard-to-figure-out problem (inexplicable non-rendering of web fonts) that turned out to be caused by optimizeLegibility
in the past, so from now on that's going to be a prime suspect when things behave strangely in Chrome.
(nb. Even if you don't think you're using it, if you're using a framework like Twitter Bootstrap you may be using it unwittingly)
Upvotes: 2
Reputation: 253318
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>
You could, also, just comment-out the between div
s:
<div class="list-container">
</div><!--
--><div class="button-container">
</div>
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;
}
Upvotes: 13
Reputation: 19309
It's the margin in your body:
margin: 4px;
Because the margin counts as part of the total width. 300px for the first one + 100px for the second div + 8px (4 on either side) for the margin = 408px. That forces the second div down to the next line.
I'm actually kind of surprised that it works at 96. It acts like it's only accounting for the margin on one side. I'd expect it to only work at 92 or below. Either way account for the margin size in the width of your body or set the margin to 0 and that should fix the problem.
Upvotes: 0