固定定位元件的 100vh 替代方案?

Him*_*ora 3 html javascript css

我有一个div (top navigation)嵌套在flex容器内的。当top-nav展开时,我希望它占据视口的整个高度。我知道这可以通过设置高度来实现,100vh但并未得到广泛支持。所以,我需要一种更传统的方式来实现这一点。

htmlbody有一个height 100%,但该视图的内容溢出,我可以滚动页面。

我现在拥有的是:

.top-nav .top-nav-links-wrapper {
    position: fixed;
    width: 100%;
    background-color: #fff;
    top: 50px;
    left: 0;
    height: 100%;        
}
Run Code Online (Sandbox Code Playgroud)

有没有办法实现这一点(除了将高度设置为100vh)?

小智 7

强烈建议不要在网页中使用vw/ 。vhSafari 对它们的支持非常差,尤其是 iPhoneX* 的缺口。

另一个答案提供了一个可靠的替代方案,使用positiontopright和。bottomleft

position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
Run Code Online (Sandbox Code Playgroud)

将占据第一个祖先的 100%,其位置不同于默认位置static

使用position: fixed将使其占据整个布局视口。

当您在 iPhoneX 上有凹口时,100vw 在 iOS Safari 的测量中包含凹口,即使您的 DOM 不包含凹口。

100vh 并不是您期望的 iOS Safari 上的值(它比 100 视口高度稍高一些)。

window.innerHeight/Widthdocument.documentElement.clientHeight/WidthSafari 中的另一个一致性噩梦,但这是另一天的话题。

我在一个十亿用户网站上工作,因此不得不禁止我的团队在我们的代码中使用vw/ 。vh


Sov*_*iut 5

视口单位喜欢vh并且vw得到很好的支持;使用它们。

另一种选择是将位置fixed设置为并设置bottom: 0height假定父元素的高度并且不考虑位置、边距或填充;bottom假定与父容器底部的偏移量。这同样适用于widthVS right。请记住,您不应同时使用heightbottom,否则它们会相互覆盖。

这是一个工作示例。

.fullscreen {
  position: fixed;
  top: 50px;
  left: 0;
  right: 0;
  bottom: 0;
  
  background: cornflowerblue;
}

.body {
  height: 2000px;
}
Run Code Online (Sandbox Code Playgroud)
<div class="fullscreen">this will be fullscreen with a top offset</div>

<div class="body">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sed arcu quis dui congue pulvinar. Ut scelerisque suscipit ipsum, in elementum velit aliquet sit amet. Nulla tempus iaculis vestibulum. Mauris eu odio id dui consectetur blandit facilisis nec metus. Nullam laoreet risus et aliquam viverra. Sed eu imperdiet metus. Vivamus at dui turpis.</p>
</div>
Run Code Online (Sandbox Code Playgroud)

无论您使用哪种单位,页面始终能够在展开的导航后面滚动。如果您的导航栏也有固定位置,那么这应该不是问题,因此它可以跟随。