如何在相对div内使div高度100%?

时间:2016-03-25 10:15:25

标签: html css css-position

这是我的代码:

<div class="parent">
  <div class="child-1"> CHILDREN 1 </div>
  <div class="child-2"> CHILDREN 2 </div>
  <div class="child-3"> CHILDREN 3 </div>
</div>

CSS:

.parent {
  position: relative;
  height: 250px;
}
.child-1 {
  position: absolute;
  top: 0;
  width: 100%;
}
.child-2 {
  height: 100%;
}
.child-3 {
  position: absolute;
  bottom: 0;
  width: 100%;
}

我将child-2设为 100%,但没有发生。那么,如何使 .child-2 高度100%以及在child-1和child-3之间?

4 个答案:

答案 0 :(得分:2)

假设我理解你想要做什么......这似乎是FlexBox®船长的工作。

.parent {
  display: flex;
  flex-direction: column;
  
  width: 300px;
  height: 200px;
  background: Yellow;
}
.child-1 {
  background: Red;
}
.child-2 {
  flex-grow: 1;
  
  background: Green;
}
.child-3 {
  background: Blue;
}
<div class="parent">
  <div class="child-1"> CHILDREN 1 </div>
  <div class="child-2"> CHILDREN 2 </div>
  <div class="child-3"> CHILDREN 3 </div>
</div>

重要的部分是在容器上设置display: flex,指示渲染引擎按flex规则计算,将方向更改为垂直flex-direction: column并仅使中间子填充使用flex-grow: 1增加所有剩余空间。

答案 1 :(得分:0)

也许如果从.child中删除position: absolute;,你就会得到你想要的,因为在你的情况下你会得到.child-2 div。顶部的.child-2。

试试这个:

.parent {
  position: relative;
  height: 250px;
}
.child-1 {
  top: 0;
  width: 100%;
}
.child-2 {
  height: 100%;
}
.child-3 {
  bottom: 0;
  width: 100%;
}

答案 2 :(得分:0)

您可以为此

使用 display:table-cell 属性

答案 3 :(得分:0)

将您的孩子2添加到css:

以下
.child-2 {
height: 100%;
position: absolute;
top: 50%;
bottom: 50%;
}

你的孩子3级排名前100%:

.child-3 {
position: absolute;
bottom: 0;
width: 100%;
top: 100%;
}

child-2将成为其他两个div的中间位置。