如果有人发布过相同的问题,请原谅我,我找不到类似问题的答案。
当我单击带有 #dotNetComponents url 的按钮时,它会将我带到带有 dotNetComponents ID 的 div,但有点过头了,切断了标题和一些文本。我相信原因是因为我的标题很粘,但我不是 100% 确定这一点。无论如何,我需要在目标的顶部添加一个缓冲区,这样 div 就不会被切断。四处搜索后,我找到了下面的 css,看起来应该可以正常工作。当我将 css 从 :target 更改为 :hover 时,我能够看到页面在我将鼠标悬停在带有 ID 的 div 上时主动进行更改。因此,问题出在 :target 选择器本身。请帮忙。
这是我的 html 的简化版本:
<a href="#dotNetComponents" class="btn transformBtn">.NET COMPONENTS</a>
<div id="dotNetComponents" class="interiorContent container offsetAnchor">
</div>
这是CSS:
#dotNetComponents:target::before {
display: block;
content: " ";
margin-top: -110px;
height: 110px;
visibility: hidden;
pointer-events: none;
}
最佳答案
CSS 滚动
如果您使用链接只是为了在页面内导航 :target
不需要也不需要 ::before
.
在下面的演示中:
block 元素环绕目标元素(例如
<article>
)前面提到的元素具有这些必需的属性:
从链接滚动时的一个常见问题是目标元素可能离链接太近——请注意目标元素有一个 100vh margin-top/bottom
.边距的大小由您决定,但我建议采用将目标推离屏幕的边距。此外,如果目标元素位于页面底部,它只会向上滚动到 margin-bottom
。或父元素 padding-bottom
.
overflow-y: scroll; /* Adds a persistent vertical scrollbar */ scroll-behavior: smooth; /* Animates scrolling */ height: 150px; /* This varies as long as it's a fixed height. */
演示
nav a {
font-size: 15vh;
width: 30%;
display: inline-block;
text-align: center
}
article {
overflow-y: scroll;
scroll-behavior: smooth;
height: 150px;
}
section {
margin: 100vh auto;
height: 110px;
line-height: 110px;
border: 3px solid #000;
font-size: 15vh;
text-align: center;
}
<nav>
<a href="#A">A</a>
<a href="#B">B</a>
<a href="#C">C</a>
</nav>
<article>
<section id="A">A</section>
<section id="B">B</section>
<section id="C">C</section>
</article>
关于html - :target pseudo selector not selecting target,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54877515/