提问者:小点点

CSS3 100VH在移动浏览器中不恒定


我有一个很奇怪的问题...在每个浏览器和移动版本中,我都遇到了这种行为:

  • 当您加载页面时,所有浏览器都有一个顶部菜单(例如,显示地址栏),当您开始滚动页面时,该菜单向上滑动。
  • 100vh有时只在视区的可见部分计算,因此当浏览器栏向上滑动时,100vh会增加(以像素为单位)
  • 由于尺寸已更改,所有布局重新绘制并重新调整
  • 对用户体验的不良影响

如何才能避免这个问题?当我第一次听说viewport-height时,我很兴奋,我想我可以用它来处理固定高度块,而不是使用javascript,但现在我认为唯一的方法是javascript和一些调整大小事件...

您可以在以下站点看到问题:sample site

有谁能帮助我/建议一个CSS解决方案吗?

简单测试代码:

null

/* maybe i can track the issue whe it occours... */
$(function(){
  var resized = -1;
  $(window).resize(function(){
    $('#currenth').val( $('.vhbox').eq(1).height() );
    if (++resized) $('#currenth').css('background:#00c');
  })
  .resize();
})
*{ margin:0; padding:0; }

/*
  this is the box which should keep constant the height...
  min-height to allow content to be taller than viewport if too much text
*/
.vhbox{
  min-height:100vh;
  position:relative;
}

.vhbox .t{
  display:table;
  position:relative;
  width:100%;
  height:100vh;
}

.vhbox .c{
  height:100%;
  display:table-cell;
  vertical-align:middle;
  text-align:center;
}
<div class="vhbox" style="background-color:#c00">
  <div class="t"><div class="c">
  this div height should be 100% of viewport and keep this height when scrolling page
    <br>
    <!-- this input highlight if resize event is fired -->
    <input type="text" id="currenth">
  </div></div>
</div>

<div class="vhbox" style="background-color:#0c0">
  <div class="t"><div class="c">
  this div height should be 100% of viewport and keep this height when scrolling page
  </div></div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

null


共2个答案

匿名用户

不幸的是这是故意的…

这是一个众所周知的问题(至少在safari mobile中是这样),这是故意的,因为它可以防止其他问题。Benjamin Poulain回复了一个webkit bug:

这完全是故意的。我们费了不少工夫才达到这个效果。:)

基本问题是:当滚动时,可见区域会动态变化。如果我们相应地更新CSS视口高度,则需要在滚动期间更新布局。这不仅看起来像狗屎,而且在大多数页面中,以60 FPS的速度执行这一操作几乎是不可能的(60 FPS是iOS的基准帧率)。

很难向你展示“看起来像狗屎”的部分,但想象一下,当你滚动时,内容在移动,你想要的屏幕也在不断变化。

动态更新高度不起作用,我们有几个选择:在iOS上删除视图单元,像iOS 8之前一样匹配文档大小,使用小视图大小,使用大视图大小。

从我们得到的数据来看,使用更大的视图大小是最好的折衷方案。大多数使用viewport单元的网站在大多数时候看起来都很棒。

Nicolas Hoizey对此做了大量研究:https://nicolas-hoizey.com/2015/02/viewport-height-is-taller-than-the-visible-part-of-the-document-in-some-mobile-browsers.html

未计划修复

在这一点上,除了避免在移动设备上使用视口高度之外,没有什么可以做的了。Chrome在2016年也做了这样的改变:

  • https://groups.google.com/a/chromium.org/forum/#!topic/blink-dev/bk0ohurgmj4
  • https://developers.google.com/web/updates/2016/12/url-bar-resizing

匿名用户

您可以在css中尝试min-height:-webkit-fill-available;而不是100vh。应该解决