How to Maintain a Div\'s Aspect Ratio Based on Its Height Using CSS?

Linda Hamilton
Release: 2024-11-02 05:05:02
Original
535 people have browsed it

How to Maintain a Div's Aspect Ratio Based on Its Height Using CSS?

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>
Copy after login

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>
Copy after login

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>
Copy after login
<code class="css">.demo {
  width: 90vw;
  height: 90vh;
  overflow: auto;
  resize: both;
  outline: 1px solid #999;
}</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!