Home >Web Front-end >CSS Tutorial >How to Maintain Div Aspect Ratio Based on Height Using CSS?

How to Maintain Div Aspect Ratio Based on Height Using CSS?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-03 13:48:30775browse

How to Maintain Div Aspect Ratio Based on Height Using CSS?

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:

  • It establishes a fixed relationship between an element's height and width.
  • As a result, the box's aspect ratio (in this case, 2:1) is maintained regardless of window height changes.

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!

Statement:
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