Home > Web Front-end > CSS Tutorial > How Can I Maintain Aspect Ratio When Responsively Resizing a Div with CSS?

How Can I Maintain Aspect Ratio When Responsively Resizing a Div with CSS?

DDD
Release: 2024-12-23 19:14:17
Original
901 people have browsed it

How Can I Maintain Aspect Ratio When Responsively Resizing a Div with CSS?

Responsively Alter Div Dimensions While Preserving Aspect Ratio

When working with images, applying a percentage value to their width or height maintains their aspect ratio as they expand or shrink. However, replicating this behavior with other elements can be challenging.

Fortunately, CSS offers a solution to link the width and height of an element using percentages, ensuring its aspect ratio remains consistent.

Solution Using CSS

This can be achieved through the surprising fact that the padding-top property's percentage value is relative to the containing block's width. Consider the following CSS snippet:

.wrapper {
  width: 50%;
  display: inline-block;
  position: relative;
}
.wrapper:after {
  padding-top: 56.25%;
  display: block;
  content: '';
}
.main {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  background-color: deepskyblue;
  color: white;
}
Copy after login

HTML Example:

<div class="wrapper">
  <div class="main">
    This is your div with the specified aspect ratio.
  </div>
</div>
Copy after login

In this example, the ".wrapper" div sets the width to 50% (or any desired percentage) and creates a relative context for the inner ".main" div.

The ".wrapper:after" pseudo-element uses the padding-top property to establish a 56.25% padding ratio. This ratio represents a 16:9 aspect ratio, ensuring that the ".main" div always maintains that aspect ratio.

Finally, the ".main" div fills the entire ".wrapper" container while preserving its aspect ratio and showcasing its deepskyblue background and white text.

The above is the detailed content of How Can I Maintain Aspect Ratio When Responsively Resizing a Div with 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template