3

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

Example illustration: enter image description here

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

There has to be more than one element sharing the same style. I've tried drawing it, but I dont know if this makes much sense. The individual squares need to fit the outer divs, but the three squares should not be the same size - rather fit their individual outer div.

enter image description here

I would like to give and idea of how I've tried doing this, but it is difficult to go into details because I've done a lot of things - none of them really working. I've tried absolute positioning, but that requires a width. I've tried calculating the width/height using jquery - this takes waaaay to long - as there are a lot of entries. I've tried using height:100% + width:auto, which renders nothing, I've tried the above solution that I've linked to (which is brilliant, yes sadly is based onthe width as a percent and not the height). etcetcetc!! :)

The solution in the question this has been linked to is not sufficient for my problem.

4 Answers4

2

There is, unfortunately, no straight forward way to implement this in CSS alone. You could use viewport units as others have mentioned, but this is always relative to the entire viewport size. It turns out Javascript is the only way to make it more flexible:

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>
Midas
  • 7,012
  • 5
  • 34
  • 52
1

Try this:

width: 100vh;
height: 100vh;

Demo:

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

jsFiddle

Stickers
  • 75,527
  • 23
  • 147
  • 186
1

.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>
Saika
  • 398
  • 3
  • 14
0

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 works in this example