Justify divs with CSS to fill width of parent container [duplicate]
I have a page with a container width 100% so its the entire width of the screen, i have several DIVs in a grid structure, they all have float: left on them and no set width, just a margin of 10px.
Is there a method, using CSS or jQuery, to have the divs fill the entire width and justify themselves to fit the gaps, so the margin changes depending the screen size.
Check out thirtydot's answer in this thread for a pure CSS/HTML solution without JavaScript that works in all browsers including IE 6.
Fluid width with equally spaced DIVs
http://jsfiddle.net/thirtydot/EDp8R/
HTML:
<div id="container">
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
<div class="box4"></div>
<span class="stretch"></span>
</div>
CSS:
#container {
border: 2px dashed #444;
height: 125px;
text-align: justify;
-ms-text-justify: distribute-all-lines;
text-justify: distribute-all-lines;
/* just for demo */
min-width: 612px;
}
.box1, .box2, .box3, .box4 {
width: 150px;
height: 125px;
vertical-align: top;
display: inline-block;
*display: inline;
zoom: 1
}
.stretch {
width: 100%;
display: inline-block;
font-size: 0;
line-height: 0
}
.box1, .box3 {
background: #ccc
}
.box2, .box4 {
background: #0ff
}
Using CSS3 this is now super easy.
UPDATE
Added MS IE support (believe in it or not...). I'm not pretty sure about the FF stuff because Mozilla changed something. I have not so much time. So if someone could maybe correct me...
UPDATE II
Moved code to snippet
.container {
border: 1px solid black;
display: -webkit-box;
-webkit-box-pack: justify;
-webkit-box-align: center;
display: -moz-box;
-moz-box-pack: justify;
-moz-box-align: center;
display: -ms-flexbox;
-ms-flex-pack: justify;
-ms-flex-align: center;
display: box;
box-pack: justify;
box-align: center;
}
.child {
background-color: red;
}
<div class="container">
<div class="child">
Some Content
</div>
<div class="child">
Some Content
</div>
<div class="child">
Some Content
</div>
</div>
You can do this with CSS if specify all dimensions in percents (ie. width, margin, padding).
Or if you want a specific margin or padding, you can use jQuery
$(window).resize(function() {
var $columns = $('.column'),
numberOfColumns = $columns.length,
marginAndPadding = 0,
newColumnWidth = ($('#container').width() / numberOfColumns) - marginAndPadding,
newColumnWidthString = newColumnWidth.toString() + "px";
$columns.css('width', newColumnWidthString);
}).resize();