Home  >  Article  >  Web Front-end  >  How to Vertically Align Dynamically Sized Divs with CSS?

How to Vertically Align Dynamically Sized Divs with CSS?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 10:53:30197browse

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:

  • vertical-align: middle aligns the image vertically within the #wrap element, regardless of its height.
  • line-height: 0 removes the default line spacing for the #wrap element, ensuring that it has no intrinsic height.
  • By setting text-align: center and line-height to the desired container height, we establish a baseline that aligns the image vertically within the container.
  • The #center element is used for positioning the container vertically within the parent container and is centered using CSS transforms.

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!

Statement:
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