Reputation: 5554
I would like to know if it is possible to have divs of various percentages fill their parent container completely like how table cells will always fill the width of their row even when the percentages need to be rounded.
Here is the desired effect using a table: http://jsfiddle.net/Tq9mJ/1/
Here is what happens when using divs with the same percentage: http://jsfiddle.net/fDVwB/1/
I would really prefer to use divs in my specific application if it is possible.
Thanks!
Edit: The div example appears to work at some resolutions. The problem is apparent if you look at each example while horizontally resizing your browser window. The table cells consitantly fill while the divs sometimes leave empty space.
Upvotes: 2
Views: 2378
Reputation: 1785
The biggest problem is the ENTER/space between the divs, at least one space is rendered. This makes that you have 3 items of 33.33333% + 3 spaces of width. This doesn't fit in the parent. of you put the begin and end div right next to each other, The do fit.
I have played a bit with your example and now it looks like this:
div.container
{
width: 90%;
margin: 10px auto;
height: 100px;
border: 1px solid #999;
}
div.container>div{
display:inline-block;
margin:0;
padding:0;
width: 33.333%;
height: 100%;
}
div.left
{
background-color: Red;
}
div.center
{
background-color: Blue;
}
div.right
{
background-color: Aqua;
}
<div class="container">
<div class="left"></div><div class="center"></div><div class="right"></div>
</div>
Upvotes: 0
Reputation: 6356
In your div example, adding a few more "3"s to the end of your percentage helped a little bit.
Another CSS method would be with CSS3 flex-box declarations. JSFiddle webkit-only example here. Unfortunately, browser support isn't good (no IE), but it's a beautifully clean way to achieve what you need.
Edit: A good post by John Resig discusses this problem and the difficulty in making it perfect, although it doesn't offer any additional guidance.
Upvotes: 1
Reputation: 5227
The problem is that, since your parent container uses percent, which boils down to the finest level of sub-pixel precision offered by CSS, adding child elements whose widths are a percentage of the parent's already fully-precise width, the floating point numbers needed to express their actual width in pixels requires more precision than CSS can afford. Apparently, when faced with a value too precise for its rendering engine, browsers will, by default, round down, leaving tiny margins of unfilled space when an element's exact width can't be expressed with perfect precision.
A sort of kludgy workaround for this quirk is to assign your .right div a padding-left: .25% and margin-right: -.25%. This will supplement the apparent width of the div without bumping it to the next line.
Hope this helps!
Upvotes: 1