Maintaining Div Aspect Ratio Based on Height Using CSS
In certain scenarios, you may need to ensure that an element's width remains a percentage of its height, regardless of the height's variability. While a JavaScript solution exists for this, CSS may also provide an elegant approach.
To achieve this, utilize the aspect-ratio property:
<code class="css">.box { height: 50%; background-color: #3CF; aspect-ratio: 2 / 1; }</code>
Here's where the aspect-ratio property truly shines:
This solution ensures that the element's width is always 50% of its height, even when the window is resized vertically.
The above is the detailed content of How to Maintain Div Aspect Ratio Based on Height Using CSS?. For more information, please follow other related articles on the PHP Chinese website!