deshg
deshg

Reputation: 1253

How to center unknown number of fluid divs in a 100% width container?

I have a 100% width container (within another parent div) which contains up to 6 fluid width items inside it which are each 1/6 of the container width (16.66%)

When there are 6 child divs then this obviously works fine but if there are less then i want them to retain the same width (1/6 of the full 100% parent width) but to horizontally center within the container.

If i use margins or padding on the container (or create a wrapper within the container) then it affects the percentage width of the items (as it changes the total width that the percentages relate to).

I could obviously use absolute positioning and JS to fix this but would like to be able to do it via CSS if at all possible.

Could anyone shed any light on what approach should be taken in this scenario?

I have created a simple jsfiddle to illustrate what i mean: http://jsfiddle.net/9L4Qd/

Code from jsfiddle:

body, html {
    height: 100%;
}
body {
    margin: 0;
    padding: 0;
}
#container {
    width: 100%;
    height: 100%;
    background-color: #000000;
}

#container div {
    width: 16.66%;
    float: left;
}

<div id="container">
 <div style="background-color: #ffcc00;">
    Option 1
 </div>
 <div style="background-color: #cccc00;">
    Option 2
 </div>
 <div style="background-color: #ffcc00;">
    Option 3
 </div>
 <div style="background-color: #cccc00;">
    Option 4
 </div>
 <div style="background-color: #ffcc00;">
    Option 5
 </div>
</div>

Thanks very much,

Dave

Upvotes: 1

Views: 95

Answers (1)

Paulie_D
Paulie_D

Reputation: 115047

Instead of floats use display:inline-block

JSfiddle with 6 divs

Jsfiddle with 5 divs

CSS

body, html {
    height: 100%;
}
body {
    margin: 0;
    padding: 0;
}
#container {
    width: 100%;
    height: 100%;
    background-color: #000000;
    text-align: center;
    font-size: 0;
}

#container div {
    width: 16.66%;
    display: inline-block;
    font-size:1rem
}

Upvotes: 3

Related Questions