Centering floating divs within another div

Darren picture Darren · Aug 13, 2009 · Viewed 211.9k times · Source

I've searched other questions and, while this problem seems similar to a couple of others, nothing I've seen so far seems to address the issue that I'm having.

I have a div which contains a number of other divs, each of which is floated left. These divs each contain a photo and a caption. All I want is for the group of photos to be centered within the containing div.

As you can see from the code below, I've tried using both overflow:hidden and margin:x auto on the parent divs, and I've also added a clear:both (as suggested in another topic) after the photos. Nothing seems to make a difference.

Thank you. I appreciate any suggestions.

<div style="position: relative; margin: 0 auto; overflow: hidden; text-align: center;">
    <h4>Section Header</h4>

    <div style="margin: 2em auto;">

        <div style="float: left; margin: auto 1.5em;">
            <img src="photo1.jpg" /><br />
             Photo Caption
        </div>
        <div style="float: left; margin: auto 1.5em;">
            <img src="photo2.jpg" /><br />
             Photo Caption
        </div>
        <div style="float: left; margin: auto 1.5em;">
            <img src="photo3.jpg" /><br />
             Photo Caption
        </div>

        <div style="clear: both; height: 0; overflow: hidden;"> </div>

    </div>

</div>

Answer

Sampson picture Sampson · Aug 13, 2009

First, remove the float attribute on the inner divs. Then, put text-align: center on the main outer div. And for the inner divs, use display: inline-block. Might also be wise to give them explicit widths too.


<div style="margin: auto 1.5em; display: inline-block;">
  <img title="Nadia Bjorlin" alt="Nadia Bjorlin" src="headshot.nadia.png"/>
  <br/>
  Nadia Bjorlin
</div>