Home > Article > Web Front-end > How to Vertically Align Dynamically Sized Divs with CSS?
Vertical Alignment of Dynamically Sized Divs with CSS
In the world of CSS, achieving perfect alignment can be a challenge, especially when dealing with divs of unknown or dynamic sizes. Consider the following scenario: you have a div containing an image or flash object, and you want to align it vertically within its parent container, regardless of the container's or child's dimensions.
Solution:
CSS provides an elegant solution for this dilemma. Utilizing the combination of vertical-align: middle and line-height: 0, we can achieve both horizontal and vertical centering within a container of indeterminate size.
HTML Structure:
<code class="html"><span id="center"> <span id="wrap"> <img src="http://lorempixum.com/300/250/abstract" alt="" /> </span> </span></code>
CSS Styles:
<code class="css">html, body { height: 100%; width: 100%; padding: 0; margin: 0; overflow: hidden; } #center { position: relative; display: block; top: 50%; margin-top: -1000px; height: 2000px; text-align: center; line-height: 2000px; } #wrap { line-height: 0; } #wrap img { vertical-align: middle; }</code>
Explanation:
Note for Internet Explorer 7: To ensure compatibility with IE7, the innermost elements (#wrap and ) should be declared on a single line, as demonstrated in this modified HTML structure:
<code class="html"><span id="center"> <span id="wrap"><img src="http://lorempixum.com/300/250/abstract" alt="" /></span> </span></code>
This pure CSS2 solution provides reliable alignment for divs with dynamic dimensions, whether they contain images, flash objects, or other elements.
The above is the detailed content of How to Vertically Align Dynamically Sized Divs with CSS?. For more information, please follow other related articles on the PHP Chinese website!