Thoughts

Responsive Design: Automatically Center Elements without using a media query.

View Demo | Download Source

Having a responsive website that looks good in all screen sizes could be challenging. That is why I want to share a quick CSS technique that could be used to automatically center elements without the use of a media query. In this example, we will be automatically centering list items.

Let’s say you have a list of images in a grid. As you scale down the browser width, you want the images to automatically stay in the center like this:

auto-center

As you could see this method provides the flexibility of always having the elements centered regardless of the number of elements you’re trying to center. This is fairly simple to achieve and doesn’t take much CSS.

Here’s the HTML:

<div class="container">
     <ul>
        <li><img src="http://placehold.it/300x300" alt="image"/></li>
        <li><img src="http://placehold.it/300x300" alt="image"/></li>
        <li><img src="http://placehold.it/300x300" alt="image"/></li>
        <li><img src="http://placehold.it/300x300" alt="image"/></li>
        <li><img src="http://placehold.it/300x300" alt="image"/></li>
        <li><img src="http://placehold.it/300x300" alt="image"/></li>
        <li><img src="http://placehold.it/300x300" alt="image"/></li>
        <li><img src="http://placehold.it/300x300" alt="image"/></li>
        <li><img src="http://placehold.it/300x300" alt="image"/></li>
        <li><img src="http://placehold.it/300x300" alt="image"/></li>
        <li><img src="http://placehold.it/300x300" alt="image"/></li>
        <li><img src="http://placehold.it/300x300" alt="image"/></li>
        <li><img src="http://placehold.it/300x300" alt="image"/></li>
        <li><img src="http://placehold.it/300x300" alt="image"/></li>
        <li><img src="http://placehold.it/300x300" alt="image"/></li>                
     </ul>
</div> <!-- eo .container -->

Here’s the CSS:

.container {
    max-width: 1280px;
    margin: 40px auto;
}
ul {
    display: block;
    text-align: center;
    width: 100%;
    padding: 0;
    margin: 0;
}
li {
    display: inline-block;
    list-style: none;
    width: 300px;
    padding: 0;
    margin: 8px;
}

This method works best when you set a width and a height to the elements, but all of the elements do not need to be the same exact same size for it to work. The spacing will change if the elements do not share the same height, like this:

auto-center-height

It is important to note that this method will not work if the list items are floated. This method also does not work in IE7 and below because of the lack of support for “display: inline-block;” But this method should work in IE8 and all other modern browsers.

 

 

 

  • Share by Email