Home > Web Front-end > CSS Tutorial > How to Maintain Aspect Ratio in Auto-Resizing Divs?

How to Maintain Aspect Ratio in Auto-Resizing Divs?

Barbara Streisand
Release: 2024-11-20 18:42:16
Original
667 people have browsed it

How to Maintain Aspect Ratio in Auto-Resizing Divs?

Maintaining Aspect Ratio in Auto-Resizing Div Elements

Problem Statement

Create a div element that:

  • Automatically adjusts its size to fit available screen space
  • Maintains its original aspect ratio when resized
  • Fits within specified width and height dimensions

Solution

Utilizing the aspect-ratio property, you can achieve the desired behavior:

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: 
    /* this gradient is a proof that the ratio is maintained since the angle is fixed */
    linear-gradient(30deg,red 50%,transparent 50%),
    chocolate;
}
Copy after login

Explanation

  • aspect-ratio: var(--r): Defines the desired aspect ratio (960px : 540px)
  • width: Calculates the width based on the smaller of:

    • 90% of the available window width
    • 960px
    • 90% of the window's height multiplied by the aspect ratio
  • Linear Gradient Background: Demonstrates how the background pattern retains its aspect ratio while resizing.

This solution allows you to create a div that automatically resizes, maintaining its original aspect ratio, within the specified maximum dimensions.

The above is the detailed content of How to Maintain Aspect Ratio in Auto-Resizing Divs?. 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