Home >Web Front-end >CSS Tutorial >How to Maintain Aspect Ratio and Center a Div Using CSS?

How to Maintain Aspect Ratio and Center a Div Using CSS?

Susan Sarandon
Susan SarandonOriginal
2024-10-29 08:35:02840browse

How to Maintain Aspect Ratio and Center a Div Using CSS?

Maintaining Aspect Ratio According to Width and Height

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.

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.

Centering Div Horizontally and Vertically

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%);

Example Code

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.

Additional Notes

  • The aspect-ratio property is not yet supported in all browsers, but is supported in modern browsers like Chrome, Firefox, and Safari.
  • To ensure compatibility with older browsers, you can use polyfills like [picturefill](https://github.com/scottjehl/picturefill) or [respond.js](https://github.com/scottjehl/Respond).

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!

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