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

标签 html css

我有问题,我有一个固定的容器,里面有绝对的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;
}

最佳答案

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

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

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

Updated Fiddle

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

关于html - 为什么我不能使绝对 div 高度 100%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38699224/

相关文章:

javascript - 使用其他单选按钮更改单选按钮的值

html - 向右浮动垂直对齐

html - 是嵌入图片标题的</img>标签吗?

javascript - 如何为表格中的每一列设置背景颜色?

css - 第 n 个 child 及之前

html - 叠加/重叠元素

html - flexbox 定位,一项在顶部,一项在底部

javascript - 如何以多步骤形式为进度条制作一系列步骤?

javascript - 屏蔽没有 type=password 的输入字符

html - 使 2 个元素恰好位于彼此下方