Home >Web Front-end >CSS Tutorial >How to Maintain Aspect Ratio and Center a Div Using CSS?
Ensuring a div maintains its aspect ratio is essential for responsive design. This ensures the element's proportions remain consistent regardless of its dimensions or orientation.
To achieve this using only CSS, we can leverage the modern aspect-ratio property.
The aspect-ratio property specifies the width-to-height ratio of an element. For example, a value of 1 / 1 would create a square, while 16 / 9 would create a rectangle with the same aspect ratio as a 16:9 display.
To center an element horizontally and vertically within its parent, we can use the following CSS properties:
margin: auto; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);
Combining the aspect-ratio and centering properties, we can create a square div that maintains its aspect ratio while being centered within the viewport:
.ar-1-1 { aspect-ratio: 1 / 1; margin: auto; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 100vw; height: 100vh; }
This code will create a square div that takes up the entire viewport, while maintaining a 1:1 aspect ratio. The div will also be centered both horizontally and vertically within the viewport.
The above is the detailed content of How to Maintain Aspect Ratio and Center a Div Using CSS?. For more information, please follow other related articles on the PHP Chinese website!