Center align container and left align child elements

There isn’t an easy way to achieve the layout with plain CSS as far as I know. The following approach uses media queries to set the width of inner divs for different viewport sizes.

Consider to use Javascript if you have a rather large number of items, CSS preprocessors might be helpful too.

See code snippet and comments inline, also check out the jsfiddle example for easy testing.

body {
    margin: 10px 0;
}
.outer {
    text-align: center;
}
.inner {
    font-size: 0; /* fix for inline gaps */
    display: inline-block;
    text-align: left;
}
.item {
    font-size: 16px; /* reset font size */
    display: inline-block;
    margin: 5px; /* gutter */
}
.item img {
    vertical-align: top;
}
@media (max-width: 551px) { /* ((100+5+5)x5)+1 */
    .inner {
        width: 440px; /* (100+5+5)x4 */
    }
}
@media (max-width: 441px) {
    .inner {
        width: 330px;
    }
}
@media (max-width: 331px) {
    .inner {
        width: 220px;
    }
}
@media (max-width: 221px) {
    .inner {
        width: 110px;
    }
}
<div class="outer">
    <div class="inner">
        <div class="item"><img src="https://dummyimage.com/100"></div>
        <div class="item"><img src="https://dummyimage.com/100"></div>
        <div class="item"><img src="https://dummyimage.com/100"></div>
        <div class="item"><img src="https://dummyimage.com/100"></div>
        <div class="item"><img src="https://dummyimage.com/100"></div>
    </div>
</div>

Leave a Comment