Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center align a collection of inline-block elements without centering each element

Tags:

html

css

layout

I have a complex hierarchy structure in my code that can't really be changed. It is a collection of inline-block divs that contain images, inside of an outer div. Something like this:

<div> <!-- text-align: center -->
    <div><img/></div><!-- display: inline-block -->
    <div><img/></div><!-- display: inline-block -->
    <div><img/></div><!-- display: inline-block -->
    <div><img/></div><!-- display: inline-block -->
    <!-- ... -->
</div>

I need these images to fill the screen based on the users browser window. I also need the images themselves to be left-aligned - so if the browser can fit 5 images per row, and the last row has only 1 image, that image needs to be all the way to the left, not centered. However, I need the entire group to be center aligned, so we don't have a huge white margin on the right side.

I have tried adding another div in the hierarchy, something like this:

<div><!-- text-align: center -->
    <div><!-- display: inline-block -->
        <div><img/></div><!-- display: inline-block -->
        <div><img/></div><!-- display: inline-block -->
        <div><img/></div><!-- display: inline-block -->
        <div><img/></div><!-- display: inline-block -->
        <!-- ... -->
    </div>
</div>

This does not work, as the middle div ends up being at full width, despite being inline-block. An example can be found here: http://jsfiddle.net/cwmRw/

Any ideas on how I can do this? Thanks!

like image 641
Dustin Wilhelmi Avatar asked Aug 31 '25 03:08

Dustin Wilhelmi


1 Answers

You can do this using CSS3 Media Queries by setting the width of the div based on different resolution bounding values. I've copied the css here, in case jsfiddle doesn't keep it around forever.

.img-block{
    max-width: 160px;
    max-height: 160px;
}
.div-block{
    display: inline-block;
}
.img-container{
    margin-left: auto;
    margin-right: auto;
}

@media all and (min-width:984px){
    .img-container{
        width: 985px;
    }
}

@media all and (min-width:820px) and (max-width: 984px){
    .img-container{
        width: 820px;
    }
}
@media all and (min-width:656px) and (max-width:820px){
    .img-container{
        width: 656px;
    }
}
@media all and (min-width:492px) and (max-width:656px){
    .img-container{
        width: 492px;
    }
}
@media all and (min-width:328px) and (max-width:492px){
    .img-container{
        width: 328px;
    }
}
@media all and (min-width:164px) and (max-width:328px){
    .img-container{
        width: 164px;
    }
}

Here's a modified version of the original code http://jsfiddle.net/hxHuV/9/

like image 54
Matthew Copeland Avatar answered Sep 02 '25 18:09

Matthew Copeland