How to maintain the aspect ratio of a div but fill screen width and height in CSS?

Spread the love

Sometimes, we want to maintain the aspect ratio of a div but fill screen width and height in CSS.

In this article, we’ll look at how to maintain the aspect ratio of a div but fill screen width and height in CSS.

How to maintain the aspect ratio of a div but fill screen width and height in CSS?

To maintain the aspect ratio of a div but fill screen width and height in CSS, we can set the height of the div to a height measured in vw.

For instance, we write

div {
  width: 100vw;
  height: 56.25vw;
  background: pink;
  max-height: 100vh;
  max-width: 177.78vh;
  margin: auto;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

to set the height of the div to 56.25vw;

vw is the percentage width of the viewport.

And we set the max-height and max-width to the max height and width we allow.

Conclusion

To maintain the aspect ratio of a div but fill screen width and height in CSS, we can set the height of the div to a height measured in vw.

Leave a Reply

Your email address will not be published.