position:sticky在Chrome中为元素添加一些空间

时间:2017-03-15 08:39:36

标签: html css css3 google-chrome sticky

描述

我有一个<header>元素,当用户滚过页面时,它会使用position: sticky贴在页面顶部。不知何故,在Chrome中,所述元素不会按预期显示,而是在元素的顶部和左侧添加一些空间。我设法将我的CSS文件中的代码隔离出来以重现该错误并在Chrome(Android和Windows 7桌面)中成功复制它。有谁知道为什么会这样,以及是否有解决方案?

代码示例(也可用作Codepen

body {
  margin: 0;
}

header {
  display: block;
  height: 44px;
  background: #263238;
  color: #fafafa;
  padding: 2px 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.18), 0 2px 3px rgba(0, 0, 0, 0.26);
  white-space: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
}

header.sticky {
  position: -webkit-sticky;
  position: sticky;
  z-index: 1101;
  top: 0;
}
<p>Blah blah</p>

<header class="sticky"> 
  <button>Home</button> 
  <button>About</button>
</header>

<!-- some spacing to allow users to scroll the page -->
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>

错误和预期行为的屏幕截图

下图显示了<header>元素在所有浏览器中的外观。目前,Chrome似乎无法正确显示(请参阅下一张图片)。

Intended behavior

此图片显示了Chrome中<header>元素的外观。注意元素左侧和顶部留下的小空间。

enter image description here

注释

  • 据我所知,我的其他CSS并没有真正干扰元素的样式,正如你可以从Codepen和提供的代码片段中看到的那样。
  • 由于我的CSS框架中出现了这个错误,项目的名称和徽标已从屏幕截图中删除,以避免自我推销。
  • 如果没有上一个注释,我更倾向于使用纯CSS解决方案(没有Javascript或对HTML进行更改),除非没有。
  • 我可以在Android 5.0 5.0上的Chrome 56.0.2924.87和Windows 7(64位)上的Chrome 57.0.2987.98(64位)中成功重现该错误。

2 个答案:

答案 0 :(得分:1)

现在我可以看到你想说的话,box:shadow在这种情况下是邪恶的。我假设您无法将其删除,因此我在overflow:hidden css中添加了body。 看看下面的片段。

body {
  margin: 0;
  overflow:hidden;
  background: red
}

header {
  display: block;
  height: 44px;
  background: #263238;
  color: #fafafa;
  padding: 2px 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.18), 0 2px 3px rgba(0, 0, 0, 0.26);
  white-space: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
}

header.sticky {
  position: -webkit-sticky;
  position: sticky;
  z-index: 1101;
  top: 0;
}
<p>Blah blah</p>

<header class="sticky"> 
  <button>Home</button> 
  <button>About</button>
</header>

<!-- some spacing to allow users to scroll the page -->
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>

答案 1 :(得分:-3)

将不受支持的position: sticky替换为position: fixed; width: 100%;,并在所有浏览器上进行尝试。正如@aje所提到的,在使用实验/新css3样式之前,请始终检查浏览器兼容性。