Centering Floating Divs Within Another Div
Answer :
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> With Flexbox you can easily horizontally (and vertically) center floated children inside a div.
So if you have simple markup like so:
<div class="wpr"> <span></span> <span></span> <span></span> <span></span> <span></span> </div> with CSS:
.wpr { width: 400px; height: 100px; background: pink; padding: 10px 30px; } .wpr span { width: 50px; height: 50px; background: green; float: left; /* **children floated left** */ margin: 0 5px; } (This is the (expected - and undesirable) RESULT)
Now add the following rules to the wrapper:
display: flex; justify-content: center; /* align horizontal */ and the floated children get aligned center (DEMO)
Just for fun, to get vertical alignment as well just add:
align-items: center; /* align vertical */ DEMO
I accomplished the above using relative positioning and floating to the right.
HTML code:
<div class="clearfix"> <div class="outer-div"> <div class="inner-div"> <div class="floating-div">Float 1</div> <div class="floating-div">Float 2</div> <div class="floating-div">Float 3</div> </div> </div> </div> CSS:
.outer-div { position: relative; float: right; right: 50%; } .inner-div { position: relative; float: right; right: -50%; } .floating-div { float: left; border: 1px solid red; margin: 0 1.5em; } .clearfix:before, .clearfix:after { content: " "; display: table; } .clearfix:after { clear: both; } .clearfix { *zoom: 1; } JSFiddle: http://jsfiddle.net/MJ9yp/
This will work in IE8 and up, but not earlier (surprise, surprise!)
I do not recall the source of this method unfortunately, so I cannot give credit to the original author. If anybody else knows, please post the link!
Comments
Post a Comment