使子div成为父母的一半

时间:2021-01-15 21:28:03

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 ?

我有一个父div和一个子div。我希望孩子有父div的半宽和半高。我不能使用任何特定值(例如:500px)或任何视点单位(vh&vw) /百合维度。那么有没有任何方法可以继承父div的一半维度?

2 个解决方案

#1


8  

The answer is using percentages of parent's dimensions as the child width & height if you are using CSS

如果使用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>

#2


0  

Use width:50% and height:50%. It will use 50% of the corresponding parent property.

使用宽度:50%,高度:50%。它将使用50%的相应父属性。

#1


8  

The answer is using percentages of parent's dimensions as the child width & height if you are using CSS

如果使用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>

#2


0  

Use width:50% and height:50%. It will use 50% of the corresponding parent property.

使用宽度:50%,高度:50%。它将使用50%的相应父属性。