Scale square div according to height ratio

I need to create a square with 100% scaling in height and width according to the height and so that it always maintains the aspect ratio.

Illustration example: enter image description here

A popular example of scaling a square div is width ( https://spin.atomicobject.com/2015/07/14/css-responsive-square/ ). I would like to solve this with CSS / flexbox, but I cannot find the right solution. (IE and legacy browser support are not important)

There must be more than one element in the same style. I tried drawing it, but I don't know if that makes sense. Separate squares should correspond to external divs, but three squares should not be the same size - rather, they are suitable for their individual external div.

enter image description here

, , , - . , . / jquery - waaaay, . : 100% + width: auto, , , ( , , , , ), etcetcetc!!:)

, , .

+4
4

:

width: 100vh;
height: 100vh;

:

body {
  margin: 0;
}
.square {
  width: 100vh;
  height: 100vh;
  background: grey;
  margin: auto;
}
<div class="square"></div>
Hide result

jsFiddle

+2

, CSS. , , . , Javascript - :

document.addEventListener('DOMContentLoaded', function() {
    var el = document.getElementById('square');

    (window.onresize = function() {
        el.style.width = el.clientHeight + 'px';
    })();
});
html, body {
    height: 100%;
    margin: 0;
}
#container {
    background: red;
    height: 80%;
}
#square {
    background: lime;
    height: 100%;
    margin: auto;
}
<div id="container">
    <div id="square"></div>
</div>
Hide result
+1

You can work with Vh and calc

for this html

<div class="square"></div>

you can use this css

body {
  background-color: #515151;
}

.square {
  margin: 1vh auto;
  background-color: #cacaca;
  height: 98vh;
  width: calc(99vh * 0.8);
}

you can see how it works in this example

0
source

.row {
display:table;
  width:100%;
} 
.row div {
display:table-cell;
  vertical-align:top;
 
}
.col-1 ,.col-3{
background-color:red;}
.col-2 {
background-color:green;
}
<div class=row>
  <div class="col-1">1</div>
  <div class="col-2">2</div>
  <div class="col-3">3</div>
  
</div>
Run codeHide result
0
source

All Articles