如何使子 div 成为绝对定位父容器的高度的 100%?

7
如何使子 div 成为 position 为 absolute 和 fixed 的父容器的高度的100%?
HTML:
<div class="parent">
  <div class="child">
  </div>
</div> 

CSS

.parent {
    position: absolute;
    top0;
    right0;
    bottom0;
    left0; 
}
6个回答

4
一种方法是将父元素设置为flex容器,这样子元素就会默认被拉伸:

.parent {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  border: 2px solid red;
  display: flex;
}

.child {
  background: blue;
}
<div class="parent">
  <div class="child">
    text
  </div>
</div>


1
很简单:JSFiddle。你只需要给子
标签添加100%的高度即可。为了证明它确实有效,我改变了父级
标签的顶部和底部,这样你就可以看到子级是其父级的100%。
.parent {
  position: absolute;
  top: 25px;
  right: 0;
  bottom: 25px;
  left: 0;
  background: steelblue;
}

.child {
  height: 100%;
  width: 50%;
  background: pink;
}

在某些情况下,除非您相对于子元素给出位置,否则这将无法正常工作。 - Atul Rajput
@Atul,这些条件是什么? - Temani Afif
@Atul,我尝试将子元素的位置设置为绝对位置,它仍然有效,你所说的条件是什么? - Jos van Weesel

0
使用子div的100%高度,例如:
.Child{
height:100%;
}

0

你只需要添加一个高度为100%

.parent {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-color: #eee;
}

.child {
    width: 100px;
    height: 100%;
    background-color: blue;
}
<div class="parent">
  <div class="child">
  </div>
</div>


-1

这里有一个替代方案:

在父元素上使用position: relative,在子元素上使用height: 100%

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

.parent {
  position: relative;  
}
.child {
  position: absolute;
  height: 100%;  
}

这里有一个CodePen演示


-2

你应该给子 div 设置 100vh 的高度,例如:

.child{
 height:100vh;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接