How to Responsively Change Div Size Preserving Aspect Ratio
When resizing images, it's easy to maintain their aspect ratio by setting either their width or height as a percentage. However, achieving the same effect for non-image elements may seem challenging. Can we link the width and height of a div using percentages to maintain aspect ratio during resizing?
Solution
Absolutely! CSS offers an ingenious solution to this problem. While it may seem counterintuitive, padding-top percentages actually relate to the containing block's width. This allows us to create a dynamic height based on the specified width.
Consider the following CSS code:
.wrapper { width: 50%; /* Set the desired width */ display: inline-block; position: relative; } .wrapper:after { padding-top: 56.25%; /* 16:9 aspect ratio */ display: block; content: ''; } .main { position: absolute; top: 0; bottom: 0; right: 0; left: 0; background-color: deepskyblue; color: white; }
In the HTML, we'll wrap the div we want to resize with a class of "wrapper":
<div class="wrapper"> <div class="main"> This is your div with the specified aspect ratio. </div> </div>
This CSS creates a pseudo-element (::after) within the "wrapper" div. By setting its padding-top as a percentage of the wrapper's width, we effectively fix the aspect ratio of the div within it. As the wrapper resizes, so does the pseudo-element, ensuring that the contained div ("main") always maintains the desired aspect ratio.
The above is the detailed content of How to Maintain Aspect Ratio of a Div During Resizing Using CSS?. For more information, please follow other related articles on the PHP Chinese website!