Home > Web Front-end > CSS Tutorial > How to Vertically Align Images in Dynamically-Sized Containers?

How to Vertically Align Images in Dynamically-Sized Containers?

Susan Sarandon
Release: 2024-12-31 12:38:10
Original
582 people have browsed it

How to Vertically Align Images in Dynamically-Sized Containers?

Vertically Aligning Images in Dynamic Height Containers

Problem: How can one vertically align images within responsive containers whose heights are determined by the browser based on their width?

Solution:

1. Using Inline Elements for Vertical Alignment:

To vertically align inline elements within a parent element, create a block-level (pseudo-)element as the first child and set its height to 100% of its parent. Additionally, apply vertical-align: middle to the pseudo-element and the target image element.

2. Benefits:

  • Dynamic container dimensions are supported.
  • Image dimensions need not be explicitly specified.
  • Can be used to align inline or div elements vertically, with the option of resetting the font size for div elements to display their content.

3. Responsive Container with Vertical Image Alignment:

To create a responsive container with a height that adapts to its width, use a percentage value for the padding-top property.

4. Adding Content to the Responsive Container:

Use a wrapper element within the responsive container to house the content. Position the wrapper absolutely and expand it to fill the container's space.

HTML Code:

<div class="responsive-container">
    <div class="dummy"></div>
    <div class="img-container">
        <img src="image.jpg" alt="">
    </div>
</div>
Copy after login

CSS Code for Vertical Alignment:

.img-container {
    text-align: center;
    font: 0/0 a;
}

.img-container:before {
    content: ' ';
    display: inline-block;
    vertical-align: middle;
    height: 100%;
}

.img-container img {
    vertical-align: middle;
    display: inline-block;
}
Copy after login

CSS Code for Responsive Container:

.responsive-container {
    position: relative;
}

.responsive-container .wrapper {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}
Copy after login

The above is the detailed content of How to Vertically Align Images in Dynamically-Sized Containers?. For more information, please follow other related articles on the PHP Chinese website!

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