Can I scale a div's height proportionally to its width using CSS?

Solution 1:

You can do it with the help of padding on a parent item, because relative padding (even height-wise) is based on the width of the parent element.

CSS:

.imageContainer {
    position: relative;
    width: 25%;
    padding-bottom: 25%;
    float: left;
    height: 0;
}

img {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
}

This is based on this article: Proportional scaling of responsive boxes using just CSS

Solution 2:

Another great way to accomplish this is to use a transparent image with a set aspect ratio. Then set the width of the image to 100% and the height to auto. That unfortunately will push down the original content of the container. So you need to wrap the original content in another div and position it absolutely to the top of the parent div.

<div class="parent">
   <img class="aspect-ratio" src="images/aspect-ratio.png" />
   <div class="content">Content</div>
</div>

CSS

.parent {
  position: relative;
}
.aspect-ratio {
  width: 100%;
  height: auto;
}
.content {
  position: absolute;
  width: 100%;
  top: 0; left: 0;
}

Solution 3:

You can use View Width for the "width" and again half of the View Width for the "height". In this way you're guaranteed the correct ratio regardless of the viewport size.

<div class="ss"></div>

.ss
{
    width: 30vw;
    height: 15vw;
}

Fiddle

Solution 4:

use aspect-ratio

.my-div1{
  width: 100px;
  aspect-ratio: 16/9;
  background-color: black;
  margin-top: 10px;
}
.my-div2{
  width: 100px;
  aspect-ratio: 3/4;
  background-color: black;
  margin-top: 10px;
}
.my-div3{
  width: 100px;
  aspect-ratio: 1/1;
  background-color: black;
  margin-top: 10px;
}
.my-div4{
  width: 100px;
  aspect-ratio: 3/9;
  background-color: black;
  margin-top: 10px;
}
<div class="my-div1">
</div>
<div class="my-div2">
</div>
<div class="my-div3">
</div>
<div class="my-div4">
</div>