Languages
[Edit]
EN

CSS - set HTML element's size with aspect ratio

0 points
Created by:
Kevin
797

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>

 

References

  1. aspect-ratio - CSS: Cascading Style Sheets | MDN

Alternative titles

  1. CSS - set HTML element's height based on width
  2. CSS - set HTML element's width based on height
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join