Aspect ratio helps keep the shape of an element consistent, no matter the screen size. It stops images or boxes from looking stretched or squished.
0
0
Aspect ratio in CSS
Introduction
When you want images to keep their natural shape on different devices.
To make video players keep the right width and height ratio.
For cards or boxes that should stay square or a fixed shape.
When designing responsive layouts that adjust but keep proportions.
Syntax
CSS
selector {
aspect-ratio: width / height;
}The aspect-ratio property takes a ratio like 16 / 9 or 1 / 1.
This ratio controls the width to height proportion of the element.
Examples
This keeps the image width and height in a 16:9 ratio.
CSS
img {
aspect-ratio: 16 / 9;
}This makes a square box 200px wide and 200px tall.
CSS
div.square { aspect-ratio: 1 / 1; width: 200px; background-color: lightblue; }
The video will fill the container width and keep a 4:3 shape.
CSS
video {
aspect-ratio: 4 / 3;
width: 100%;
}Sample Program
This example shows a coral colored box that stays in a 16:9 shape. The width is 300px, and the height adjusts automatically to keep the shape.
CSS
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Aspect Ratio Example</title> <style> .box { aspect-ratio: 16 / 9; width: 300px; background-color: coral; color: white; display: flex; align-items: center; justify-content: center; font-family: Arial, sans-serif; font-size: 1.5rem; border-radius: 0.5rem; margin: 1rem auto; text-align: center; } </style> </head> <body> <div class="box">This box keeps a 16:9 shape</div> </body> </html>
OutputSuccess
Important Notes
If you set only width or height, the other dimension adjusts to keep the aspect ratio.
Aspect ratio works well with images, videos, and divs for consistent shapes.
Older browsers may not support aspect-ratio, so check compatibility if needed.
Summary
Aspect ratio keeps elements from stretching or squishing.
Use aspect-ratio: width / height; to set the shape.
It helps make responsive designs look neat and consistent.