It’s all about ratio
. You need to calculate the ratio between the rectange width
& frame width
.
Sample code here..
function renderBox() {
const width = document.getElementById('width').value;
const height = document.getElementById('height').value;
const box = document.getElementById('box');
let scale = 1;
while(true) {
if (width <= (400 * scale) && height <= (200 * scale)) {
break;
}
scale++;
}
box.style.width = width / (400 * scale) * 100 + '%';
box.style.height = height / (200 * scale) * 100 + '%';
document.getElementById('top').innerText = (200 * scale) + "px";
document.getElementById('end').innerText = (400 * scale) + "px";
}
.container {
margin-top: 20px;
width: 400px;
height: 200px;
}
.frame {
background-color:rgb(200,200,200);
width: 100%;
height: 100%;
}
.scale #start {
float:left;
}
.scale #end {
float:right;
}
.scale #top {
position: absolute;
top: 0px;
left: 10px;
}
#box {
background-color: red;
position: relative;
top: 100%;
transform:translateY(-100%);
left: 0;
}
<div class="container">
<div class="frame">
<div id='box'></div>
</div>
<div class="scale">
<span id='top'>200px</span>
<span id='start'>0px</span>
<span id='end'>400px</span>
</div>
</div>
<br><br>
width: <input type="number" id='width'> <br><br>
height: <input type="number" id='height'> <br><Br>
<button onclick='renderBox()'>Render</button>
0
solved dynamic rectangular or square div of any size which can be fitted into a fixed size div [closed]