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>
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 ...
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 ofobject-fitis clear:Unfortunately there is no way in CSS to make a regular element behave the same as a replaced element.