Home >Web Front-end >CSS Tutorial >How Can I Maintain Aspect Ratio Without JavaScript?
Maintain Aspect Ratio with Proportionally Adjusted Width
Maintaining the aspect ratio of an element based on its height without utilizing JavaScript can be a challenge. One might consider using padding-left as a percentage of the height, but this method proves ineffective.
Consider the following markup:
<code class="html"><div class="box"> <div class="inner"></div> </div></code>
The goal is to maintain the box's aspect ratio according to its height, which changes dynamically based on a percentage margin:
<code class="css">.box { position: absolute; margin-top: 50%; bottom: 0; } .inner { padding-left: 200%; }</code>
Fortunately, a native CSS solution exists: the aspect-ratio property. This property allows you to set the ratio of the element's width to its height.
<code class="css">.box { height: 50%; background-color: #3CF; aspect-ratio: 2 /1; }</code>
In this example, the box has a fluid height of 50% and an aspect ratio of 2:1. As you resize the container, the box will maintain its aspect ratio, ensuring it always remains proportionally balanced.
The above is the detailed content of How Can I Maintain Aspect Ratio Without JavaScript?. For more information, please follow other related articles on the PHP Chinese website!