Home >Web Front-end >CSS Tutorial >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:
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>
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; }
CSS Code for Responsive Container:
.responsive-container { position: relative; } .responsive-container .wrapper { position: absolute; top: 0; right: 0; bottom: 0; left: 0; }
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!