How to resize div as largest possible square in container using CSS? If this is not possible with CSS, how can this be done with JavaScript?
If the container has height > width
, I would like the size of the square to be equal to width x width
. If the container has width > height
, I would like the size of the square to be height x height
.
When the dimensions of the container change, the dimensions of the child must be adjusted accordingly.
I found this answer to help maintain the proportions of the child. This approach does not work when the width of the container is greater than the height, as the child overflows the parent object, as shown in the following snippet.
.flex { display: flex; } .wide, .tall { flex: none; border: 3px solid red; } .wide { width: 150px; height: 100px; } .tall { width: 100px; height: 150px; } div.stretchy-wrapper { width: 100%; padding-bottom: 100%; position: relative; background: blue; } div.stretchy-wrapper>div { position: absolute; top: 0; bottom: 0; left: 0; right: 0; color: white; font-size: 24px; text-align: center; }
<div class="flex"> <div class="wide"> <div class="stretchy-wrapper"> <div>Wide container</div> </div> </div> <div class="tall"> <div class="stretchy-wrapper"> <div>Tall container</div> </div> </div> </div>
source share