Aspect Ratio
by adil_invideo
HTML
<div class="parent" id="parent">
<div class="child" id="child">
</div>
<h3 class="info" id="info">
wow
</h3>
</div>
SCSS
.parent {
width: 500px;
height: 400px;
background: wheat;
display: flex;
align-items: center;
justify-content: center;
.child {
width: 50px;
height: 50px;
background: lightblue;
}
}
.info{
position: absolute;
right: 10px;
top:0;
color: blackl
}
JavaScript
// Ti adjust the child within the given width and height of the parent element while maintaing
// the given aspect ratio.
// handles both the cases of parent being portrait or landscape
// to test calculation: https://calculateaspectratio.com/
const child = document.getElementById("child");
const parent = document.getElementById("parent");
const parentWidth = parent.clientWidth;
const parentHeight = parent.clientHeight;
const aspectRatio = "1:1";
let height = child.clientHeight;
let width = child.clientWidth;
const isLandscape = () => parentHeight < parentWidth;
switch (aspectRatio) {
case "1:1":
const dimen = Math.min(parentHeight, parentWidth);
height = dimen;
width = dimen;
break;
case "9:16":
if (isLandscape()) {
height = parentHeight;
width = height * (9 / 16);
} else {
width = parentWidth;
height = width * (16 / 9);
if (height > parentHeight) {
width = parentHeight * (9 / 16);
height = width * (16 / 9);
}
}
break;
case "16:9":
if (isLandscape()) {
height = parentHeight;
width = height * (16 / 9);
if (width > parentWidth) {
height = parentWidth * (9 / 16);
width = height * (16 / 9);
}
} else {
width = parentWidth;
height = width * (9 / 16);
}
break;
case "4:3":
if (isLandscape()) {
height = parentHeight;
width = height * (4 / 3);
if (width > parentWidth) {
height = parentHeight * (3 / 4);
width = height * (4 / 3);
}
} else {
width = parentWidth;
height = width * (3 / 4);
}
break;
}
document.getElementById("info").innerHTML = "width : " + width + "<br/>height : " + height;
child.style.height = (height) + "px";
child.style.width = (width) + "px";