Resize the div to the maximum possible square in the container

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> 
+6
source share
1 answer
  • Get the width and height of all .stretchy-wrapper and parent using map ().
  • Using the for loop now gives it the maximum value.
  • Then $ (window) .resize call the resizeDiv function when resizing the browser window.

 $(document).ready (function () { function resizeDiv () { var stretchyWrapper = $(".stretchy-wrapper"), sWrapperWidth = stretchyWrapper.map (function () { return $(this).width (); }), sWrapperHeight = stretchyWrapper.map (function () { return $(this).height (); }), container = stretchyWrapper.map (function () { return $(this).parent (); }); for (var i in container) { var maxVal = Math.max (sWrapperWidth[i], sWrapperHeight[i]); $(container[i]).css ({"width": maxVal, "height": maxVal}); } } resizeDiv (); $(window).resize (function () { resizeDiv (); }); }); 
 .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; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <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> 
0
source

Source: https://habr.com/ru/post/1015193/


All Articles