I have a (horizontally) centered outer div containing two elements of unknown width:
<div style='width:800px; margin:0 auto'>
<div style='float:left'>...</div>
<div style='float:right'>...</div>
</div>
Both floats are top-aligned by default, and are of varying/unknown and different heights. Is there any way to make them vertically centered?
I eventually made the outer div
display: table
and the inner divs
display: table-cell;
vertical-align: middle;
text-align: left/right;
but I'm just curious if there's a way to do this with the floats.
You can't do this directly, because floats are aligned to the top:
If there is a line box, the outer top of the floated box is aligned with the top of the current line box.
The exact rules say (emphasis mine):
- A floating box's outer top may not be higher than the top of its containing block.
- The outer top of a floating box may not be higher than the outer top of any block or floated box generated by an element earlier in the source document.
- The outer top of an element's floating box may not be higher than the top of any line-box containing a box generated by an element earlier in the source document.
- A floating box must be placed as high as possible.
That said, you can take advantage of rule #4:
display: inline-block
.vertical-align
to align these wrapper vertically.Be aware that some space might appear between the inline-block wrappers. See How to remove the space between inline-block elements? to fix it.
.float-left {
float: left;
}
.float-right {
float: right;
}
#main {
border: 1px solid blue;
margin: 0 auto;
width: 500px;
}
/* Float wrappers */
#main > div {
display: inline-block;
vertical-align: middle;
width: 50%;
}
<div id="main">
<div>
<div class="float-left">
<p>AAA</p>
</div>
</div>
<div>
<div class="float-right">
<p>BBB</p>
<p>BBB</p>
</div>
</div>
</div>