如何计算动态元素的高度?

How can I calculate the height of dynamic elements?

本文关键字:元素 高度 动态 何计算 计算      更新时间:2023-09-26

下面是我的代码:

.parent{
  position: fixed;
  border: 1px solid;
  height:  40%;
  width: 300px;
  max-height: 200px;
}
.first_child{
  border: 1px solid blue;
  padding: 10px;
  height: 20px;
  text-align: center;
}
.second_child{
  border: 1px solid red;
  height: 100%;
  overflow-y: scroll;
}
<div class="parent">
  <div class="first_child">title</div>
  <div class="second_child">
    one<br>two<br>three<br>four<br>five<br>six<br>seven<br>eight<br>night<br>ten<br>
  </div>
</div>

如你所见,.second_child脱离了parent。我想把它保存在.parent元素中。我该怎么做呢?

换句话说,我想实现这样的东西:

.second_child{
  height: 100% - 40px;    
              /* 40px: 20px of .first_child's height, 10+10px of .first_child's padding */ 
  ...
}

注意:我不想使用calc()或box-sizing: border-box; ..因为像IE7这样的旧浏览器不支持它们。所以我在寻找第三种方法

这样的东西会起作用吗?

.parent{
  position: relative;
  border: 1px solid;
  height: 100%;
  width: 300px;
  max-height: 200px;
  min-height: 100px;
}
.first_child{
  border: 1px solid blue;
  padding: 10px;
  height: 20px;
  text-align: center;
}
.second_child{
  border: 1px solid red;
  overflow-y: scroll;
  position: absolute;
  top: 40px;
  right: 0;
  bottom: 0;
  left: 0;
}
<div class="parent">
  <div class="first_child">title</div>
  <div class="second_child">
    one<br>two<br>three<br>four<br>five<br>six<br>seven<br>eight<br>night<br>ten<br>
  </div>
</div>