Home > Web Front-end > CSS Tutorial > How to Maintain Aspect Ratio of a Div During Resizing Using CSS?

How to Maintain Aspect Ratio of a Div During Resizing Using CSS?

Mary-Kate Olsen
Release: 2024-12-31 21:28:18
Original
643 people have browsed it

How to Maintain Aspect Ratio of a Div During Resizing Using CSS?

How to Responsively Change Div Size Preserving Aspect Ratio

When resizing images, it's easy to maintain their aspect ratio by setting either their width or height as a percentage. However, achieving the same effect for non-image elements may seem challenging. Can we link the width and height of a div using percentages to maintain aspect ratio during resizing?

Solution

Absolutely! CSS offers an ingenious solution to this problem. While it may seem counterintuitive, padding-top percentages actually relate to the containing block's width. This allows us to create a dynamic height based on the specified width.

Consider the following CSS code:

.wrapper {
  width: 50%; /* Set the desired width */
  display: inline-block;
  position: relative;
}
.wrapper:after {
  padding-top: 56.25%; /* 16:9 aspect ratio */
  display: block;
  content: '';
}
.main {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  background-color: deepskyblue;
  color: white;
}
Copy after login

In the HTML, we'll wrap the div we want to resize with a class of "wrapper":

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

This CSS creates a pseudo-element (::after) within the "wrapper" div. By setting its padding-top as a percentage of the wrapper's width, we effectively fix the aspect ratio of the div within it. As the wrapper resizes, so does the pseudo-element, ensuring that the contained div ("main") always maintains the desired aspect ratio.

The above is the detailed content of How to Maintain Aspect Ratio of a Div During Resizing 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