Home >Web Front-end >CSS Tutorial >How Can I Maintain Aspect Ratio When Responsively Resizing a Div with CSS?
Responsively Alter Div Dimensions While Preserving Aspect Ratio
When working with images, applying a percentage value to their width or height maintains their aspect ratio as they expand or shrink. However, replicating this behavior with other elements can be challenging.
Fortunately, CSS offers a solution to link the width and height of an element using percentages, ensuring its aspect ratio remains consistent.
Solution Using CSS
This can be achieved through the surprising fact that the padding-top property's percentage value is relative to the containing block's width. Consider the following CSS snippet:
.wrapper { width: 50%; display: inline-block; position: relative; } .wrapper:after { padding-top: 56.25%; display: block; content: ''; } .main { position: absolute; top: 0; bottom: 0; right: 0; left: 0; background-color: deepskyblue; color: white; }
HTML Example:
<div class="wrapper"> <div class="main"> This is your div with the specified aspect ratio. </div> </div>
In this example, the ".wrapper" div sets the width to 50% (or any desired percentage) and creates a relative context for the inner ".main" div.
The ".wrapper:after" pseudo-element uses the padding-top property to establish a 56.25% padding ratio. This ratio represents a 16:9 aspect ratio, ensuring that the ".main" div always maintains that aspect ratio.
Finally, the ".main" div fills the entire ".wrapper" container while preserving its aspect ratio and showcasing its deepskyblue background and white text.
The above is the detailed content of How Can I Maintain Aspect Ratio When Responsively Resizing a Div with CSS?. For more information, please follow other related articles on the PHP Chinese website!