Center div inside 100% width container with dynamic width left and right floats
I want to have 3 divs aligned inside a container div, like this:
[[LEFT] [CENTER] [RIGHT]]
Container div is 100% wide (no fixed width), and center div should remain in center after resizing the container.
Left and Right DIV have no fixed width and need to expand/contract with the container. Center DIV does have a fixed width.
I have this:
<div style="width: 100%">
<div style="float: left; height: 50px;">&l开发者_如何转开发t;/div>
<div style="float: right; height: 50px;"></div>
<div style="margin: 0 auto; height: 50px; width: 500px;"></div>
</div>
Problem is, the left and right do not show because there is no set width
Any suggestions?
You can't do that with pure CSS. You need to use JavaScript. In the example below Middle div is fixed at 400px while remaining space is be split between left and right divs. With jQuery you can do
function calc() {
var ww = $(window).width();
var rem = ww - $('.div2').width();
$('.div1, .div3').css('width', rem / 2);
}
calc();
$(window).resize(calc);
Check working example at http://jsfiddle.net/M5Ghx/3/
Another option, if you wanted to avoid using javascript, would be to give the center div an absolute position and create two divs to use as buffers within the left and right divs:
<div style="width: 100%; text-align:center">
<div style="width:50%; height: 50px; float:left">
<div style="width:250px; height: 50px; float:right"></div>
</div>
<div style="margin-right:auto; margin-left:auto; position:absolute; left:0; right:0; width: 500px;height:50px;"></div>
<div style="width:50%; height: 50px; float:right">
<div style="width:250px; height: 50px; float:left"></div>
</div>
</div>
If you only care about Mozilla and WebKit, then you should look in to using the Flexible Box Model:
- http://hacks.mozilla.org/2010/04/the-css-3-flexible-box-model/
That will solve all your centering issues in pure CSS. Just be sure to read the docs and play around with the different options so that you understand how it works.
精彩评论