How to Align Floating Elements of Variable Heights Vertically
In a horizontally aligned container, floats tend to align to the top by default. When dealing with elements of unknown and varying heights, this alignment can lead to inconsistent and undesirable outcomes. The goal is to find a method for vertically centering these float elements without modifying their intrinsic sizing.
Restrictions of Floats
Floats are restricted in their vertical alignment due to browser specifications. Rule #8 of CSS float behavior dictates that floats must be placed as high as possible. This means that direct vertical alignment of floats cannot be achieved.
Using Inline-Block Wrappers
To circumvent this restriction, we can utilize inline-block elements to wrap our float elements. Inline-block elements establish a Block Formatting Context (BFC), allowing them to contain floats. By giving these wrappers vertical-align properties, we can control the positioning of our float elements.
Implementation
Example
<code class="css">.float-left { float: left; } .float-right { float: right; } #main { border: 1px solid blue; margin: 0 auto; width: 500px; } #main > div { display: inline-block; vertical-align: middle; width: 50%; }</code>
<code class="html"><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></code>
This approach effectively vertically centers float elements of varying heights without relying on the display property of the outer div. However, it's important to note that some space may appear between the inline-block wrappers.
The above is the detailed content of How to Vertically Align Floating Elements of Variable Heights Without Modifying Their Intrinsic Sizing?. For more information, please follow other related articles on the PHP Chinese website!