1

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

1 Answer 1

3

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
}
3
  • 1
    What happens if there are just three elements?
    – j08691
    Aug 5, 2014 at 14:54
  • The container is still 100% wide...perhaps the question is badly written.
    – Paulie_D
    Aug 5, 2014 at 15:01
  • Doh of course, not sure how I missed using inline-blocks! Thanks so much Paulie_D, you understood the question correctly that was exactly what I was trying to achieve.
    – deshg
    Aug 5, 2014 at 15:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.