How Can I Maintain Aspect Ratio Without JavaScript?

Mary-Kate Olsen
Release: 2024-11-03 07:21:03
Original
172 people have browsed it

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

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

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

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!

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