How To Preserve Aspect Ratio in CSS
![undefined / aspect, ratio, without, padding, scale, resize, original, dimensions, keep, preserve, 16:9, 4:3](https://semicolon.dev/static/css-keep-aspect-ratio.png)
To keep aspect ratio of your CSS elements, you need to use aspect-ratio property
The aspect-ratio property helps to properly scale the element relative to its original size.
#one-to-one { aspect-ratio: 1/1; max-aspect-ratio: 1/1; min-aspect-ratio: 1/1; }
Not just images. The aspect-ratio property is useful for maintaining aspect ratio of a div element, image or a video, when width or height of the element changes.
To apply aspect ratio in CSS, you need to use aspect-ratio property along with the max-aspect-ratio and min-aspect-ratio properties.
How does aspect ratio property work in CSS?
The max-aspect-ratio and min-aspect-ratio properties define the minimum and maximum aspect ratios that the element should maintain.
Here are some examples:
How to apply aspect ratio of 4:3 to an image
To maintain a 4:3 aspect ratio for an image, you can use the following code:
img { aspect-ratio: 4/3; max-aspect-ratio: 4/3; min-aspect-ratio: 4/3; }
(This will apply 4:3 ratio to all images)
You can also apply aspect ratio to videos. Usually you want to maintain 16:9 ratio.
How to apply aspect ratio of 16:9 to a video
To maintain a 16:9 aspect ratio for a video, you can use the following code:
video { aspect-ratio: 16/9; max-aspect-ratio: 16/9; min-aspect-ratio: 16/9; } <video src="video.mp4" />
This will apply 16:9 aspect ratio to all videos on the page.
How to apply aspect ratio of 1:1 to a DIV element
To maintain a 1:1 aspect ratio for a div element, you can use the following code:
#one-to-one { aspect-ratio: 1/1; max-aspect-ratio: 1/1; min-aspect-ratio: 1/1; } <!-- then in your HTML --> <div id = "one-to-one"> <!-- this element will keep aspect ratio as assigned --> </div>
Apply 1:1 ratio to a div element (CSS style example)
In these examples, the aspect-ratio property is applied to the img, video, and div elements, and the desired aspect ratio is specified using values of 4:3, 16:9, and 1:1, respectively.
The 3 aspect ratio properties will ensure that the aspect ratios of the elements are maintained as specified, regardless of the width or height of the elements.
aspect-ratio browser support
The aspect-ratio is supported in most browsers, go to this Can I Use link to find out more.