使用JS设置元素高度,然后使用JS设置子元素高度为百分比

时间:2018-07-29 15:02:10

标签: javascript html css height

我有一个子div,其中父div的高度由其所容纳的内容量(带有填充)决定。

我希望将子div的高度占父div的百分比-但很高兴,因为父级没有设置高度值,所以我无法使用CSS做到这一点。

因此,我正在尝试使用JS设置子div的高度,因此它是包含div的80%。

我知道如何获取父元素的计算出的高度值,但是我不知道如何将其设置为父元素上的实际高度值/属性-显然需要在过程中进行一个中间步骤,而我似乎无法解决该怎么做?

Codepen:https://codepen.io/emilychews/pen/EpbdYb

var parentHeight = document.querySelectorAll('.parent')[0].offsetHeight;

var child = document.querySelectorAll('.child')[0];

// i need to then set the parent height element's height to be the computed value of its .offsetHeight property.

child.style.cssText = "height: 80%;"
* {box-sizing: border-box;}

body {
  margin: 0;
  padding: 0;
  display: flex;
  width: 100%;
  height: 100vh;
  justify-content: center;
  align-items: center;
}

.parent {
padding: 8rem 2rem;
  background: red;
  width: 80%;
}

.child {
  padding: 4rem 1rem;
  width: 50%;
  height: 80%;
  background: blue;
}
<div class="parent">
  <div class="child"></div>
</div>

0 个答案:

没有答案
相关问题