CSS TIP: How to center a <div> with a variable width

June 29, 2016 Yoav Schwartz

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:

&lt;div id=&quot;container&quot; style=&quot;width:200px;margin:0 auto&quot;&gt; 
    your centered, 200 pixel wide container

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 (such as Uberflip's), 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 displays 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:

&lt;div id=&quot;wrapper&quot; style=&quot;text-align:center&quot;&gt;
  &lt;div id=&quot;container&quot; style=&quot;display:inline-block;text-align:left&quot;&gt;
       your variable width, centered container

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.

What are some handy CSS tips you've come across lately that have made your life easier? Let me know in the comments below!

About the Author

Yoav Schwartz

Yoav is the founder and CEO at Uberflip and is responsible for driving the mission, vision, and goals of the company. He spends considerable time working with his team to continuously delight and surprise Uberflip's customers.

Follow on Twitter More Content by Yoav Schwartz
Previous Article
Images too small? Try this Lightbox!
Images too small? Try this Lightbox!

You've probably seen this effect before - you're on a blog post that has an image you'd like a better look ...

Next Article
Integrate Olark With Your Hub
Integrate Olark With Your Hub