Vertical Div Alignment with Unknown Dimensions
In CSS, dynamically adjusting the vertical alignment of a div can be challenging when the div's size is unknown. Here's a solution that tackles this issue:
CSS Solution
This pure CSS solution employs vertical-align: middle within a larger div with a fixed line-height:
<code class="css">#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
The #center div is positioned at the center of its parent with top: 50% and margin-top adjustment to account for half its height. The enormous line-height ensures that the text content within it (in this case, the child div #wrap) remains at the bottom.
Inside #center, #wrap contains the image with vertical-align: middle, which ensures vertical alignment regardless of the image's size.
Caveat
The only browser with a caveat is IE7. For it, the inner div #wrap and the image must come on the same line:
<code class="html"><span id="center"> <span id="wrap"><img src="..." alt="" /></span> </span></code>
The above is the detailed content of How Can I Vertically Align a Div with Unknown Dimensions in CSS?. For more information, please follow other related articles on the PHP Chinese website!