How to Define Aspect Ratio in CSS
Code Playground is only enabled on larger screen sizes.
Instead of defining the exact with
and height
of an element. You can also define its aspect ratio like this:
<img src=". . ." alt="Image" />
img {
border: solid 1px;
width: 200px;
aspect-ratio: 16 / 9;
}
In this case, the image is set to be 200px
wide, and instead of specifying the height, we defined the aspect ratio to be 16:9
.
The browser will automatically calculate the height based on the ratio.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="/styles.css"> </head> <body> <img src="https://images.unsplash.com/photo-1538099130811-745e64318258?crop=entropy&cs=srgb&fm=jpg&ixid=M3wzMjM4NDZ8MHwxfHJhbmRvbXx8fHx8fHx8fDE3MDg2NTA0MDl8&ixlib=rb-4.0.3&q=85" alt="Image"> </body> </html>