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

How to Maintain Aspect Ratio of a Div Responsively Using Only CSS?

Mary-Kate Olsen
Release: 2024-12-21 04:17:19
Original
890 people have browsed it

How to Maintain Aspect Ratio of a Div Responsively Using Only CSS?

Responsive Div with Maintained Aspect Ratio Using CSS

When attempting to maintain an aspect ratio while resizing a div, you can leverage the power of CSS without relying on JavaScript.

CSS allows you to link the height and width of an element using percentages. Here's how to achieve it:

.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

In this example, the wrapper div sets the desired width (50%). The wrapper:after pseudo-element uses a padding-top percentage relative to the wrapper's width. The value 56.25% corresponds to a 16:9 aspect ratio.

The main div fills the entire wrapper div, maintaining the aspect ratio specified by the padding-top percentage on the wrapper:after pseudo-element.

By utilizing CSS, you can easily maintain an aspect ratio for your div while resizing it responsively, without introducing JavaScript.

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