为什么我不能使绝对 div 高度 100%

新手上路,请多包涵

我有问题,我有一个固定的容器,里面有绝对 div,我想设置 .absolute div height:100%; 为容器 div(500 像素)的全高。这是我试图解决我的问题的方法,这是因为我想创建带有切换容器的移动菜单,并且对我来说重要的是手机屏幕的高度 100%

https://jsfiddle.net/d1bh9ncs/

HTML

 <div class="container">
  <div class="fixed">
    <div class="absolute">

    </div>
  </div>
</div>

CSS

 .container{
  width:100%;
  height:500px;
  background-color:#ddd;
}
.fixed{
  position:fixed;
  width:100%;
  height:50px;
  background-color:red;
  top:8px;
  left:8px;
  right:15px;
}
.absolute{
  position:absolute;
  height:100%;
  width:100%;
  background-color:green;
  top:51px;
  left:0px;
}

原文由 ml92 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 358
2 个回答

父 div .fixed 是绝对定位的,高度为 50px。所以在它的孩子上应用 height: 100% 将继承相对高度(即50px)。

height: 100vh; .absolute 。我已经使用计算高度 height: calc(100vh - 51px) 来避免滚动条由于 top: 51px

注意vh 是视口高度(可见网页高度)的1/100。

更新小提琴

.absolute {
  position: absolute;
  height: calc(100vh - 51px);
  width: 100%;
  background-color: green;
  top: 51px;
  left: 0px;
}

原文由 Pugazh 发布,翻译遵循 CC BY-SA 3.0 许可协议

您正在使用 Fixed div 作为 Absolute div 的父 div,Absolute div 可以有 100% 的 Fixed div 如果您在 Percentage 中添加高度值,则它不能扩展到其父级的高度。如果您希望它扩展为父级高度,您必须必须以 px(像素)为单位添加高度

.container{
  width:100%;
  height:500px;
  background-color:#ddd;
}
.fixed{
  position:fixed;
  width:100%;
  height: 101px;
  background-color:red;
  top:8px;
  left:8px;
  right:15px;
}
.absolute{
  position:absolute;
  height: 117px;
  width:100%;
  background-color:green;
  top: 0px !important;
  left:0px;
  z-index: 99999999;
  top: 50px;
}

原文由 Muhammad Bilawal 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题