CSS粘滞忽略1px

iqxoj9l9  于 2023-02-17  发布在  其他
关注(0)|答案(2)|浏览(148)

我想做一个粘在顶部的导航栏,但是当它粘在上面的时候有一个小的缝隙。我没有页边空白或者填充。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <div class="topdiv"></div>
    <div class="bardiv"></div>
</body>
</html>
html, body {
    height: 200%;
    width: 100%;
    margin: 0;
    padding: 0;
}

.topdiv {
    height: 50px;
}

.bardiv {
    position: sticky;
    top: 0px;
    height: 50px;
    background-color: black;
}

它并不是在所有的缩放级别下都显示出来,例如在jsfidle上我只在175%下看到它,只有当topdiv的高度以像素为单位声明时才会出现这种情况,同时也设置了bardiv top:-1px也解决了这个问题,但我不明白为什么现在它不起作用了。
http://jsfiddle.net/daxy5mru/41/

iyfjxgzm

iyfjxgzm1#

诀窍是使用“top:-1像素”。
示例类:

.table-header {
  position: sticky;
  top: -1px;
}
mccptt67

mccptt672#

你不能简单地使用HTML和CSS,你也应该使用JavaScript来保持标题在滚动时的粘性。

// When the user scrolls the page, execute myFunction
window.onscroll = function() {
  myFunction();
};
// Get the navbar
var header = document.getElementById("Navbar");
// Get the offset position of the navbar
var sticky = header.offsetTop;
// Add the sticky class to the header when you reach its scroll position.
function myFunction() {
  if (window.pageYOffset > sticky) {
    header.classList.add("sticky");
  } else {
    header.classList.remove("sticky");
  }
}
/* Style the header */

.navbar {
  padding: 5px;
  background: #555;
}

/* Page content */

.content {
  padding: 16px;
}

/* The sticky class is added to the header with JS when it reaches its scroll position */

.sticky {
  position: fixed;
  top: 0;
  width: 100%;
}

/* Add some top padding to the page content to prevent as the header gets a new position at the top of the page (position:fixed and top:0) */

.sticky+.content {
  padding-top: 102px;
}
<div class="top-container">
  <p>Logo</p>
</div>
<div class="navbar" id="Navbar">
  <h2>your navigation bar</h2>
</div>
<div class="content">
  <p>
    Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae
    voluptatibus.
  </p>
</div>

相关问题