I couldn’t find a solution for growing a div inside div maintaining aspect-ratio except for images, but I want to do it with a div.
I basically want object-fit: contain behavior for a div inside a div, with some padding.
But it only works for wide, but not for narrow divs.
<div class="container">
<div class="element">
</div>
</div>
---
.container {
display: flex;
background: yellow;
width: 320px; /* arbitrary values for testing */
height: 190px; /* arbitrary values for testing */
justify-content: center;
align-items: center;
padding: 16px;
}
.element {
background: red;
aspect-ratio: 1 / 3;
width: 100%;
max-height: 100%;
}
This code works with aspect-ratio: 3 / 1;
but not with aspect-ratio: 1 / 3;
.
.container {
display: flex;
background: yellow;
width: 320px;
height: 190px;
justify-content: center;
align-items: center;
padding: 16px;
}
.element {
background: red;
aspect-ratio: 1 / 3;
width: 100%;
max-height: 100%;
}
<div class="container">
<div class="element">
</div>
</div>
My expected behavior is depending on the aspect-ratio (which I want to change via JavaScript later on, that the result looks like in the image below:
2
Answers
Since you want it to behave like
object-fit: contain
, the.element
should fill or the entire height or the entire width depending on which is the greater arm defined in the aspect ratio asw / h
.Now the problem is for the
.element
to have at least one of theheight
orwidth
set for the other one to be calculated according to the aspect ratio.Using
max-height
andmax-width
is not enough for that to happen unless you drop the flex layout on the container. But that means you’ll have hard time trying to center the.element
because other strategies at such conditions are not viable. Before giving up I also tried usingposition: absolute
withtransform: translate(-50%, -50%)
andleft: 50%; top: 50%
. Another solution using pseudoelements was suggested in comments but frankly I think it didn’t fulfill theobject-fit
requirement because it didn’t fill the whole available space confined by the container paddings.So to me, so far, the only solution I could find was just deciding which size to style as
100%
betweenwidth
andheight
depending on which side of the aspect ratio was the larger. So for example if the aspect ratio is1 / 3
theheight
should fill100%
otherwise thewidth
.This drawback requires you to take into account that the properties set via css should be consistent
aspect-ratio
,width
andheight
. A workaround might be using css variables and deductions made over one single value to set all of those three.By the way since you also added that js will be involved in changing the aspect ratio of the element, it seemed to me legit to deal with it via javascript applying the strategy I described above.
This is a short demo:
If you want to achieve this with just css, you’ll need some "hacking". For example, adding a
<canvas>
element that will store the requiredaspect-ratio
: