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

时间:2016-08-22 02:34:34

标签: javascript jquery html css

这是我的代码:

.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()或大小调整大小:border-box;。因为IE7等旧浏览器不支持它们。所以我正在寻找第三种方法。

1 个答案:

答案 0 :(得分:0)

这样的事情会起作用吗?

.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>

相关问题