Maintaining Div Aspect Ratio Based on Height Using CSS
When it comes to maintaining the proportions of an element, the traditional solution is to use a percentage value for vertical padding. However, achieving the same effect with horizontal padding is not as straightforward. This article explores a CSS-based approach to preserve the aspect ratio of a div element based on its height.
The desired markup structure is as follows:
<div class="box"> <div class="inner"></div> </div>
To maintain the aspect ratio, we can leverage the CSS aspect-ratio property:
<code class="css">.box { height: 50%; background-color: #3CF; aspect-ratio: 2 / 1; }</code>
The aspect-ratio property specifies the ratio of the width to the height of the element. In this case, a ratio of 2:1 indicates that the width will be twice the height.
By setting the height of the parent element (box) to a fluid value (e.g., 50%) and adjusting its aspect-ratio property, we can ensure that its width scales proportionally with the height.
To demonstrate the effect, you can consider the following HTML and CSS code:
<code class="html"><div class="demo"> <div class="box"> <ul> <li>This box has fluid height of 50%</li> <li>It has an aspect ratio of 2:1</li> <li>Resize the container vertically (or horizontally)</li> <li>The box will maintain its aspect ratio</li> <li>The text content will not affect its width</li> </ul> </div> </div></code>
<code class="css">.demo { width: 90vw; height: 90vh; overflow: auto; resize: both; outline: 1px solid #999; }</code>
Resizing the container (.demo) will demonstrate that the box (box) adjusts its width while maintaining its 2:1 aspect ratio. This solution provides a clean and effective way to preserve the desired proportions of an element purely through CSS.
The above is the detailed content of How to Maintain a Div\'s Aspect Ratio Based on Its Height Using CSS?. For more information, please follow other related articles on the PHP Chinese website!