Centering a div block without the width

Update 27 Feb 2015: My original answer keeps getting voted up, but now I normally use @bobince’s approach instead.

.child { /* This is the item to center... */
  display: inline-block;
}
.parent { /* ...and this is its parent container. */
  text-align: center;
}

My original post for historical purposes:

You might want to try this approach.

<div class="product_container">
    <div class="outer-center">
        <div class="product inner-center">
        </div>
    </div>
    <div class="clear"/>
</div>

Here’s the matching style:

.outer-center {
    float: right;
    right: 50%;
    position: relative;
}
.inner-center {
    float: right;
    right: -50%;
    position: relative;
}
.clear {
    clear: both;
}

JSFiddle

The idea here is that you contain the content you want to center in two divs, an outer one and an inner one. You float both divs so that their widths automatically shrink to fit your content. Next, you relatively position the outer div with it’s right edge in the center of the container. Lastly, you relatively position the inner div the opposite direction by half of its own width (actually the outer div’s width, but they are the same). Ultimately that centers the content in whatever container it’s in.

You may need that empty div at the end if you depend on your “product” content to size the height for the “product_container”.

Leave a Comment