EN
CSS - set HTML element's size with aspect ratio
0
points
In this article, we would like to show you how to set HTML elements' size with aspect ratio using CSS.
Quick solution:
.my-element {
width: 30%;
aspect-ratio: 1 / 1; /* <--- height based on width with 1/1 aspect ratio (square) */
}
Warning:
This CSS style appeared in 2021 and may not be supported by some web browsers.
Practical example
In this example, we use the aspect-ratio CSS property to create square items that resize with the web page keeping the aspect ratio.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
.container {
display: flex;
}
.item {
background: red;
margin: 5px;
width: 30%;
aspect-ratio: 1 / 1; /* <--- height based on width with 1/1 aspect ratio (square) */
}
</style>
</head>
<body>
<div class="container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</body>
</html>