Aspect ratio and replaced elements
Definition and purpose
aspect-ratio supplies a preferred width-to-height ratio used when at least one size is automatic. Replaced elements such as images may also have intrinsic dimensions and a natural ratio.
Ratio-driven box
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> #a { width: 160px; aspect-ratio: 2 / 1; background: navy; } #b { width: 160px; aspect-ratio: 1; background: green; } </style> </head> <body> <div id="a"></div> <div id="b"></div> </body></html>The ratio determines the automatic height.
Syntax and mental model
width: 160px; aspect-ratio: 2 / 1; height: auto yields 80px height for an empty simple box. For an image, its natural ratio can determine the auto size. When both dimensions are fixed, the preferred ratio usually cannot change them. object-fit: contain or cover controls how replaced content fits its box; cover can crop.
Fit an image
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> #a { width: 100px; height: 100px; object-fit: contain; } #b { width: 100px; height: 100px; object-fit: cover; } </style> </head> <body> <img id="a" alt="Wide blue swatch" src="data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 width=%27200%27 height=%27100%27%3E%3Crect width=%27200%27 height=%27100%27 fill=%27blue%27/%3E%3C/svg%3E"> <img id="b" alt="Wide blue swatch" src="data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 width=%27200%27 height=%27100%27%3E%3Crect width=%27200%27 height=%27100%27 fill=%27blue%27/%3E%3C/svg%3E"> </body></html>Contain preserves the whole image; cover fills the square and may crop.
Common mistakes
Do not force both image dimensions without considering distortion or cropping. Supply meaningful alt text and reserve space to reduce layout movement.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Overflow and scroll containers. Next lesson: Font families and fallback.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Aspect ratio and replaced elements — knowledge check
Five questions on aspect ratio and replaced elements.
What is the height of an empty 160px wide box with ratio 2 / 1?
What does aspect-ratio provide?
Which can preserve the whole image within a differently shaped box?
What can object-fit: cover do?
Why reserve image space before loading?