CSS Tip: Center a <div> With a Variable Width

Follow

Learn how to center containers like divs when the width is variable.


 

Conventional wisdom has it that if you want to center a container such as a div, your best bet is to define a width and set margin left and right to "auto". For example:

<div id="container" style="width:200px;margin:0 auto">
your centered, 200 pixel wide container
</div>

This is fine when you have a defined width, but what happens when the width varies?

There's a great example close to home - within a Hub, a set of floated Item tiles are contained in a div and are required to be centered on the page such that, for example, on a wide screen that can fit it, 6 tiles display on a single row.

Since we want a maximum of 6 tiles to display on a row, and each tile has a width of 250px, and each tile should be 20px away from its neighbor, the container width is being set to (250 + 20) * 6 = 1620px.

You'll find this in our CSS which defines the wrapper (.page-aligner) that houses the tiles container:

@media only screen and (max-width: 9999px){
.page-aligner {
width: 1620px;
}
}

While this works, it's rather limiting. If for example a Hub has only 4 Items, those 4 tiles will be off center, because the container will still be 1620px, with the last 2 spots for tiles unfilled.

There's a better way. And when I say better, I mean different.

Rather, than forcing a width to the container, we could do something like this:

<div id="wrapper" style="text-align:center">
<div id="container" style="display:inline-block;text-align:left">
your variable width, centered container
</div>
</div>

By setting your container to display inline-block (which is safe to use cross-browser), it can be aligned according to the text-align property. You'll notice I set the #container's text alignment to "left" to return it to the default.

In this example, rather than setting a width on the wrapper, we could set a max-width instead. That will force the 7th tile to wrap in this case.

It will also mean not having to define any break-points for smaller screens as now the screen width will determine smaller widths for that wrapper.

0 out of 0 found this helpful

Comments

0 comments

Please sign in to leave a comment.