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!