【问题标题】::target pseudo selector not selecting target:target 伪选择器不选择目标
【发布时间】:2019-07-19 12:35:34
【问题描述】:

如果有人发布过同样的问题,请原谅我,我无法找到类似问题的答案。

当我单击带有#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;
 }

【问题讨论】:

  • 它看起来不错,似乎是working,你可能有其他干扰。

标签: html css pseudo-class


【解决方案1】:

CSS 滚动

如果您使用链接只是在页面内导航,则不需要:target,也不需要::before

在以下演示中:

  • 块元素包裹在目标元素周围(例如&lt;article&gt;

  • 前面提到的元素具有这些必需的属性:

从链接滚动时的一个常见问题是目标元素可能离链接太近——请注意,目标元素有一个 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-08
    • 2014-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多