Resizing Child Div Proportionally with Parent Container on Both Axes

59 Views Asked by At

I have a parent container with a child div set to an aspect ratio of 2/1.

When I resize the parent along the x-axis, the child scales accordingly. However, resizing along the y-axis doesn't affect the child. How can I address this?

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    .parent {

      display: flex;

      position: absolute;
      background-color: blue;
      width: 50%;
      height: 50%;
      resize: both;
      overflow: auto;
      align-items: center;
      justify-content: center;
    }

    .child {

      display: flex;
      position: relative;
      aspect-ratio: 2/1;
      width: 50%;
      height: auto;
      background-color: aquamarine;

    }
  </style>
</head>

<body>
  <div class="parent">
    <div class="child">
    </div>
  </div>
</body>
</html>

1

There are 1 best solutions below

0
Brett Donald On

Your child has a specified width of 50% of its containing block, and a specified aspect-ratio, so yes, the only the width of the containing block will affect the size of the child.

If your child instead has a specified height of 50% of its containing block, along with a specified aspect-ratio, then the height of the containing block will affect the child, but not the width.

It doesn’t work both ways ...

.parent {
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: blue;
  width: 50%;
  height: 50%;
  overflow: hidden;
  box-sizing: border-box;
}

.child {
  height: 50%;
  aspect-ratio: 2/1;
  background-color: aquamarine;
}
<div class="parent">
  <div class="child"></div>
</div>

With a replaced element such as an image, you could use object-fit. Note that in this snippet I have left the aquamarine background on the image element so that the effect of object-fit is clear:

.parent {
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: blue;
  width: 50%;
  height: 50%;
  overflow: hidden;
  box-sizing: border-box;
}

.child {
  width: 50%;
  height: 50%;
  object-fit: contain;
  background-color: aquamarine;
}
<div class="parent">
  <img class="child" src="http://picsum.photos/500/250">
</div>

Unfortunately there is no way in CSS to make a regular element behave the same as a replaced element.