Home >Web Front-end >CSS Tutorial >How to Vertically Align Divs with Dynamic Size in CSS?

How to Vertically Align Divs with Dynamic Size in CSS?

DDD
DDDOriginal
2024-11-02 20:06:02777browse

How to Vertically Align Divs with Dynamic Size in CSS?

CSS: Vertical Alignment of Divs with Dynamic Size

When working with div elements that contain dynamic content, such as images or flash, aligning them vertically can be a challenge. Traditional methods, such as setting fixed heights or using absolute positioning, may not be feasible in these situations.

Fortunately, CSS offers a solution that allows for vertical alignment without the need for known sizes. This solution is based on the combination of vertical-align: middle and line-height: 0.

HTML Structure

<code class="html"><span id="center">
    <span id="wrap">
        <img src="image.jpg" alt="" />
    </span>
</span></code>

CSS Rules

<code class="css">html, body {
    height: 100%;
    width: 100%;
    padding: 0;
}

#center {
    position: relative;
    top: 50%;
    margin-top: -1000px;
    height: 2000px;
    text-align: center;
    line-height: 2000px;
}

#wrap {
    line-height: 0;
}

#wrap img {
    vertical-align: middle;
}</code>

How it Works

  • The #center element's line-height is set to a fixed value (e.g., 2000px) and text-align is set to center.
  • The #wrap element has its line-height set to 0.
  • The image's vertical-align is set to middle, which vertically aligns it within the line of its containing element.
  • The margin of the #center element is negative half of the element's height, which visually positions the element in the middle of the viewport.

This technique works in most modern browsers, including IE8 , and without the need for browser hacks. It offers a clean and versatile solution for vertically aligning div elements with dynamic sizes.

The above is the detailed content of How to Vertically Align Divs with Dynamic Size in 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