gpt4 book ai didi

html - 在页面向下移动一定方向后粘性标题消失

转载 作者:太空宇宙 更新时间:2023-11-04 07:31:50 25 4
gpt4 key购买 nike

我正在为我即将举行的婚礼建立一个网站,我想要一个粘性标题,但出于某种原因,当你在页面上向下移动到一定位置后,它会“消失”。我的测试网址是:https://betterradiotech.com .这是导航标记:

<!-- Start Nav -->
<header>
<nav>
<ul class="nav-list">
<li><a href="/" title="Home">Home</a></li>
<li><a href="/music/" title="Music">Music</a></li>
<li><a href="/gallery/" title="Gallery">Gallery</a></li>
<li><a href="/feed/" title="Feed">Feed</a></li>
</ul>
</nav>
</header> <!--/ End Nav -->

这是导航 SCSS:

header {
padding: 1em;
position: sticky;
top: 0;
z-index: 100;
width: 100%;
background-color: $burgandy;
}
.nav-list {
display: flex;
flex-flow: row nowrap;
li {
list-style-type: none;
margin-left: 10px;
}
a {
color: $pink;
font-weight: 600;
}
}
.active-nav {color: $navy !important;}

制作导航时没有 JavaScript,除了使事件导航正常工作...为了完整起见,我也将包括在内:

switch(location.pathname) {
case "/":
document.querySelector("a[title*='Home']").classList.add("active-nav");
break;
case "/admin/":
document.querySelector("a[title*='Admin']").classList.add("active-nav");
break;
case "/feed/":
document.querySelector("a[title*='Feed']").classList.add("active-nav");
break;
case "/gallery/":
document.querySelector("a[title*='Gallery']").classList.add("active-nav");
break;
case "/music/":
document.querySelector("a[title*='Music']").classList.add("active-nav");
break;
}

为什么我的导航栏在页面下方一定距离后消失了?它似乎发生在第一节的完整背景图片结束之前。

最佳答案

这可能是因为你的包含元素没有你想象的那么高,你可能必须显式地将该元素的height设置为fit-content,因为粘性元素不能离开他们的父级!

在大多数情况下,最简单的解决方案是将此规则添加到您的 CSS:

body {
height: fit-content;
}

但通常,您需要哪种解决方案以及必须将其应用到哪个元素取决于您的文档结构。假设它看起来像这样:

<body>
<header>
<nav>
<!-- Your navigation -->
</nav>
</header>
<main>
<!-- The main content of the site -->
</main>
</body>

您可能使用了一些包含如下规则的 CSS 重置:

html, body {
height: 100%;
}

这允许在你的页面上使用百分比高度,但它会在没有额外工作的情况下打破粘性标题。

当您使用开发工具查看主体尺寸时,一切看起来都不错:

MDN page on height property with html and body height at 100% scrolled all the way up.

但是一旦向下滚动,就会发现一个问题:

MDN page on height property with html and body height at 100% scrolled half way down, revealing the body element is too short.

body 与您的视口(viewport)一样高。您看到的所有其他内容都从中溢出。但是粘性 header 无法做到这一点,它会留在 body 中并随之消失。我们现在有三种可能的解决方案:

如果您的页面不需要基于百分比的高度,您可以使用此 CSS 规则:

body {
height: fit-content;
}

如果有一些基于百分比的高度,请尝试将它们替换为 vh,看看是否适合您。然后您可以应用上面的修复程序。

如果您确实需要基于百分比的高度,那么您可能希望让主体保持原位但滚动溢出的内容:

html {
overflow: hidden;
}

body {
overflow: scroll;
}

关于html - 在页面向下移动一定方向后粘性标题消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49324760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com