Home > Article > Web Front-end > How to Vertically Center Floating Elements of Unknown Heights?
Problem:
You have a container element that horizontally centers two floating elements of varying heights. By default, these floats align to the top of the container. How can you vertically center them?
Answer:
Direct vertical alignment of floats is not possible, as they adhere to specific alignment rules that prioritize alignment to the top. However, you can achieve this effect by exploiting the rule that floats can be contained within elements that establish a new block formatting context (BFC).
Solution:
Example:
<code class="css">.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%; }</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>
The above is the detailed content of How to Vertically Center Floating Elements of Unknown Heights?. For more information, please follow other related articles on the PHP Chinese website!