Home >Web Front-end >CSS Tutorial >How to Maintain a Div's Aspect Ratio Responsively Using Only CSS?
While CSS allows images to maintain their aspect ratio with a percentage-based width or height, the same technique may not seem directly applicable to other elements. However, it is possible to maintain the aspect ratio of a div using pure CSS.
Solution:
Leverage the fact that padding-top percentages are relative to the containing block's width. By combining this with a nested div structure, you can create an aspect ratio-locked element.
Example:
.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; }
<div class="wrapper"> <div class="main"> This is your div with the specified aspect ratio. </div> </div>
In this example, the .wrapper div has a width of 50%. A pseudo-element (.wrapper:after) is added to establish the aspect ratio—in this case, it's 16:9. The nested .main div fills the entire .wrapper div, ensuring that the content maintains the specified aspect ratio as the .wrapper div is resized.
The above is the detailed content of How to Maintain a Div's Aspect Ratio Responsively Using Only CSS?. For more information, please follow other related articles on the PHP Chinese website!