Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making child div half size of parent

Tags:

html

css

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 ?

like image 905
Ajith Avatar asked Jan 02 '15 17:01

Ajith


1 Answers

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>
like image 83
im_brian_d Avatar answered Oct 04 '22 05:10

im_brian_d