代码之家  ›  专栏  ›  技术社区  ›  JPG

为什么100%或100vh高度不占用整页高度

  •  0
  • JPG  · 技术社区  · 4 年前

    我在学习 css 伪选择器类 ::before .我很困惑为什么给 height 的属性 background-color 实际上并没有占据整页的高度。我也尝试了视口高度。同样的问题。以下是我的代码:

    * {
      margin: 0;
      padding: 0;
    }
    
     :root {
      --navbar-height: 59px;
    }
    
    #navbar {
      display: flex;
      align-items: center;
      border: 2px solid red;
    }
    
    #navbar ul {
      display: flex;
    }
    
    #navbar::before {
      content: "";
      background-color: black;
      position: absolute;
      /* height being 100% or 100vh not occupying full page */
      height: 100vh;
      width: 100%;
      z-index: -1;
      opacity: 0.4;
    }
    
    #navbar ul li {
      list-style: none;
      font-size: 1.3rem;
    }
    
    #navbar ul li a {
      display: block;
      padding: 3px 22px;
      border-radius: 20px;
      text-decoration: none;
    }
    <nav id="navbar">
      <ul>
        <li class="item"><a href="#">home</a></li>
        <li class="item"><a href="#">services</a></li>
        <li class="item"><a href="#">contactus</a></li>
      </ul>
    </nav>

    输出

    enter image description here

    我所期望的是黑色 背景色 因为被赋予了100%的高度就会占据整个页面。但这并没有发生。为什么会这样?

    3 回复  |  直到 4 年前
        1
  •  2
  •   Cristi Marian    4 年前

    问题是由于显示:flex;在#navbar上。去掉它,你就应该没事了。另一个解决方案是将导航条封装在父div中,并在上面添加::before。

        2
  •  1
  •   DeltaG    4 年前

    你只需要定位 :before 正确地将以下CSS添加到您的 #navbar::before 并且您应该设置:

    top: 0;
    left: 0;
    
        3
  •  1
  •   K-Dawg    4 年前

    因为你的定位是绝对的,所以你需要检查顶部和左侧的属性。

    我复制了你的代码,然后打开了chrome-dev工具,如所附的屏幕截图所示。如果您打开computed选项卡,您将看到顶部属性为-516.378px。

    您可以单击“元素”>Computed,它将在浏览器计算完所有特性后向您显示这些特性。

    chrome Devtools

    如果添加顶部:0;如下所示,您可以覆盖计算出的css位置。

    #navbar::before {
      content: "";
      background-color: black;
      position: absolute;
      /* height being 100% or 100vh not occupying full page */
      height: 100vh;
      width: 100%;
      top: 0;
      z-index: -1;
      opacity: 0.4;
    }
    

    这里有一个stackblitz示例,你可以自己尝试:

    https://stackblitz.com/edit/js-82vdk5?file=style.css