Home  >  Article  >  Web Front-end  >  How to Maintain Aspect Ratio of a Div Based on Width and Height?

How to Maintain Aspect Ratio of a Div Based on Width and Height?

Barbara Streisand
Barbara StreisandOriginal
2024-10-31 02:54:02351browse

How to Maintain Aspect Ratio of a Div Based on Width and Height?

Maintaining Aspect Ratio According to Width and Height

When striving to position a centered square div within the viewport, the question arises: how can one effectively preserve its aspect ratio while considering both the width and height dimensions?

The advent of the CSS aspect-ratio property in 2022 offers a comprehensive solution to this challenge. This property empowers developers to maintain any aspect ratio relative to the viewport size or the parent element.

To achieve our objective of maintaining the aspect ratio based on viewport dimensions, the following CSS code can be employed:

This code snippet exemplifies two aspect ratios: 1:1 and 1:19, respectively. The div elements utilizing these aspect ratios will automatically adjust their dimensions to maintain these ratios within the viewport, ensuring a consistent visual appearance regardless of the viewport size or orientation.

The above is the detailed content of How to Maintain Aspect Ratio of a Div Based on Width and Height?. 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