将 child div 的大小减半 parent

Making child div half size of parent

我在 it.I 上有一个 parent div 和一个 child div 希望 child 有一半的宽度和一半的高度parent div.I 不能使用任何特定值(例如:500px)或任何视点单位(vh 和 vw)/百分比 dimensions.So 是否有任何方法可以继承一半的尺寸的 parent div ?

如果您使用 CSS

,答案是使用父尺寸的百分比作为子宽度和高度

.parent {
  height: 100px;
  width: 100px;
  background: red;
}

.child {
  height: 50%;
  width: 50%;
  background: blue;
}
<div class="parent">

   <div class="child"></div>

</div>

Javascript解决方案

否则您可以将父级高度和宽度分成两半并将其设置为子尺寸..

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>

使用 width:50% 和 height:50%。它将使用相应父级 属性.

的 50%