I would like to have two columns of 50% width space, and avoid floats.
So i thought using display:inline-block
.
When the elements add to 99% width (eg 50%, 49%, http://jsfiddle.net/XCDsu/2/ ) it works as expected.
When using 100% width (eg 50%, 50%, http://jsfiddle.net/XCDsu/3/ ) the second column breaks to the second line.
Why is that?
It is because display:inline-block
takes into account white-space in the html. If you remove the white-space between the div
's it works as expected. Live Example: http://jsfiddle.net/XCDsu/4/
<div id="col1">content</div><div id="col2">content</div>
You can remove the whitespaces via css using white-space so you can keep your pretty HTML layout. Don't forget to set the white-space back to normal again if you want your text to wrap inside the columns.
Tested in IE9, Chrome 18, FF 12
.container { white-space: nowrap; }
.column { display: inline-block; width: 50%; white-space: normal; }
<div class="container">
<div class="column">text that can wrap</div>
<div class="column">text that can wrap</div>
</div>
NOTE: In 2016, you can probably use
flexbox
to solve this problem easier.
This method works correctly IE7+ and all major browsers, it's been tried and tested in a number of complex viewport-based web applications.
<style>
.container {
font-size: 0;
}
.ie7 .column {
font-size: 16px;
display: inline;
zoom: 1;
}
.ie8 .column {
font-size:16px;
}
.ie9_and_newer .column {
display: inline-block;
width: 50%;
font-size: 1rem;
}
</style>
<div class="container">
<div class="column">text that can wrap</div>
<div class="column">text that can wrap</div>
</div>
Live demo: http://output.jsbin.com/sekeco/2
The only downside to this method for IE7/8, is relying on body {font-size:??px}
as basis for em/%-based font-sizing.
IE7/IE8 specific CSS could be served using IE's Conditional comments
inline
and inline-block
elements are affected by whitespace in the HTML.
The simplest way to fix your problem is to remove the whitespace between </div>
and <div id="col2">
, see: http://jsfiddle.net/XCDsu/15/
There are other possible solutions, see: bikeshedding CSS3 property alternative?
I continued to have this problem in ie7 when the browser was at certain widths. Turns out older browsers round the pixel value up if the percentage result isn't a whole number. To solve this you can try setting
overflow: hidden;
on the last element (or all of them).
精彩评论