How can we vertically align an image within a div that has a dynamic height that adjusts to the width when the browser window is resized to maintain a square aspect ratio?
To achieve this, we can employ the following technique:
To create a responsive container, where the height adjusts with the width, we can apply a percentage value to the top/bottom padding or margin property.
To implement both vertical alignment and a responsive container, we can wrap the image element in a wrapper div with absolute positioning and expand it to fill the container's entire space.
<div class="responsive-container"> <div class="dummy"></div> <div class="img-container"> <img src="..."> </div> </div>
.responsive-container { width: 60%; position: relative; } .dummy { padding-top: 100%; /* maintains 1:1 aspect ratio */ } .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; }
This code demonstrates how to vertically align an image within a responsive container, where the container's height adjusts based on the available width.
The above is the detailed content of How to Vertically Center an Image within a Responsively Sized Div?. For more information, please follow other related articles on the PHP Chinese website!