Home > Web Front-end > CSS Tutorial > How Can I Vertically Align a Div with Unknown Dimensions in CSS?

How Can I Vertically Align a Div with Unknown Dimensions in CSS?

Barbara Streisand
Release: 2024-11-03 13:56:30
Original
647 people have browsed it

How Can I Vertically Align a Div with Unknown Dimensions in CSS?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template