1

I want to center a container div within another div, and the child divs of the container need to also be centered, but left-aligned with each other. The child divs are of variable and unpredictable width.

For example:

<div>
    <div class="container">
        <div class="child"><img />Text</div>
        <div class="child"><img />Text Widest</div>
        <div class="child"><img />T</div>
    </div>
</div>

I found a solution that works in Firefox, but need a universal solution. I also considered using JavaScript to measure the images, text, and div's, but am confident that I'm just CSS ignorant and there is a simple, elegant solution. Here is what works just in Firefox:

.container {
    width: -moz-max-content;
    margin: 0px auto 0px auto;
    border-style: solid;
}

.child {
    border-style: solid;
    margin: 0px auto 0px auto;
}
  • Does the outer most div have to have a width of 100%? If you can set a fixed width for any of them your `margin: 0 auto;` will work. – PREEB Feb 17 '12 at 21:12
  • No. The outer most div may vary in width, but that doesn't seem to eliminate the need to set a fixed or percentage width on the container div's style to get the desired layout. The problem with doing that is that a child div may exceed that width and then wrapping occurs - when setting small widths. Of course, when setting large fixed/relative widths, child div's simply don't appear centered in the container. –  Feb 17 '12 at 21:30
  • Check this out and see if you need to add a `span` and a `display: inline-block;` to your code. http://stackoverflow.com/questions/450903/make-css-div-width-equal-to-contents – PREEB Feb 17 '12 at 22:27

1 Answers1

0
.container {
   display: table; 
   margin: 0 auto; 
}
.container > .child {
  display: table-cell; 
}
gherkins
  • 14,603
  • 6
  • 44
  • 70
Marat Tanalin
  • 13,927
  • 1
  • 36
  • 52