How Can I Preserve Aspect Ratio in Auto-Resizing Div Elements Using CSS?

DDD
Release: 2024-11-20 01:49:01
Original
964 people have browsed it

How Can I Preserve Aspect Ratio in Auto-Resizing Div Elements Using CSS?

Preserving Aspect Ratio in Auto-Resizing Div Elements

Div elements can be challenging to style when they need to fit varying screen sizes while maintaining a specific aspect ratio. This can be achieved using the aspect-ratio CSS property alongside an intuitive combination of width and height attributes.

To gracefully handle both width and height changes, you can leverage the aspect ratio calculation --r = width / height. Here's how to implement it in CSS:

body {
  height: 100vh;
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: gray;
}

.stage {
  --r: 960 / 540;

  aspect-ratio: var(--r);
  width: min(90%, min(960px, 90vh * var(--r)));
  
  display: flex;
  justify-content: center;
  align-items: center;
  
  background: 
    linear-gradient(30deg, red 50%, transparent 50%),
    chocolate;
}
Copy after login

In this example:

  • --r is a custom CSS variable that stores the aspect ratio as a decimal.
  • The aspect-ratio property sets the calculated aspect ratio.
  • The width property calculates the minimum value between 90% of the available space, 960px, and 90% of the viewport height multiplied by the aspect ratio. This ensures the width remains proportionate to the height.
  • The height is determined by the aspect-ratio property in conjunction with the calculated width.

Such an approach ensures that the div element automatically resizes while maintaining the desired aspect ratio, accommodating both width and height variations.

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