Darren Darren - 3 months ago 12
HTML Question

Centering floating divs within another div

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

First, remove the float attribute on the inner divs. Then, Text-align:center on the main outer div. And for the inner divs, display:inline or display:inline-block.

Just tested it - display:inline-block on the inner divs works. 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>
Comments