I have a parent div & a child div on it.I want the child to have half width & half height of the parent div.I can't use any particular value (eg:500px) or any viewpoint units (vh & vw) / percentage dimensions.So is there any method to inherit half of the dimensions of the parent div ?
The answer is using percentages of parent's dimensions as the child width & height if you are using CSS
.parent {
height: 100px;
width: 100px;
background: red;
}
.child {
height: 50%;
width: 50%;
background: blue;
}
<div class="parent">
<div class="child"></div>
</div>
Javascript Solution
You can otherwise divide the parent height and width in half and set it as the child dimensions..
var parent = document.getElementsByClassName("parent")[0];
var child = document.getElementsByClassName("child")[0];
child.style.width = parent.offsetWidth / 2 + "px";
child.style.height = parent.offsetHeight / 2 + "px";
.parent {
height: 100px;
width: 100px;
background: red;
}
.child {
background: blue;
}
<div class="parent">
<div class="child"></div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With