Home >Web Front-end >CSS Tutorial >How Can I Maintain Aspect Ratio in a Resizable, Centered Div Element?

How Can I Maintain Aspect Ratio in a Resizable, Centered Div Element?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-26 06:01:09476browse

How Can I Maintain Aspect Ratio in a Resizable, Centered Div Element?

Maintaining Aspect Ratio in Auto-Resizing Div Elements

When creating a resizable div element that remains centered on the screen, it's important to ensure that its aspect ratio is maintained, regardless of changes in window size. This can be achieved using CSS techniques.

CSS Solution:

The aspect-ratio property provides a simple solution to maintain aspect ratio in resizing div elements. The following CSS code demonstrates how to achieve this:

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

.stage {
  --r: 960 / 540;  // Define the desired aspect ratio (width / height)

  aspect-ratio: var(--r);  // Set the aspect ratio
  width:min(90%, min(960px, 90vh*(var(--r))));  // Set the maximum width and height while preserving ratio

  display: flex;
  justify-content: center;
  align-items: center;

  background: 
    linear-gradient(30deg,red 50%,transparent 50%),  // Add a gradient to visualize the preserved aspect ratio
    chocolate;
}

Explanation:

  • The aspect-ratio property establishes the desired aspect ratio for the element, which is calculated based on the initial width and height values (960px and 540px, respectively).
  • The width property ensures that the element's width remains within the specified constraints:

    • A maximum of 90% of the available width
    • A maximum of 960px
    • A width that maintains the aspect ratio in relation to the available height (90vh multiplied by var(--r))
  • The background gradient is added to visually demonstrate that the aspect ratio is maintained, as the angle of the gradient remains constant regardless of changes in the element's dimensions.

Result:

The above CSS code results in a div element that remains centered on the screen, maintains its desired aspect ratio, and resizes to fit the available window space. This solution works effectively for resizing both the width and height of the element.

The above is the detailed content of How Can I Maintain Aspect Ratio in a Resizable, Centered Div Element?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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