【问题标题】:Using a pseudo-element (::before) as jump link target not working in CSS使用伪元素 (::before) 作为跳转链接目标在 CSS 中不起作用
【发布时间】:2020-11-03 19:20:03
【问题描述】:

我在使用伪元素 (::before) 作为锚链接时遇到问题,因为页面无法将其识别为锚,并继续转到该部分本身。我已经尝试了Nicolas Gallagher's 博客中建议的所有选项,但似乎没有任何效果。我在博客代码中看到的唯一区别是我使用 flexbox 作为列并包装内容。

这是我正在使用的 CSS

  #one, #two, #three {
  width: 5em;
  height: 5em;
  margin: 15em;
  display: flex;
  flex-flow: column wrap;
  background: blue;
}
#one::before, #two::before, #three::before {
    background: red;
    display: block;
    content: "";
    height: 150px;
    margin: -150px 0 0;
}

谢谢!

..................................................

编辑:完成!已经找到了一种更简单的方法:在同一部分中放置一个“空”(不间断空格)锚点,对读者不可见,并且不会与上部区域边缘发生冲突。

HTML:

<div id="red-container">
    <a name="red-target">&nbsp;</a>
    Hello World!
  </div>

CSS:

#red-container {
  width: 5em;
  height: 5em;
  position: relative;
  margin: 1.5em;
  /** display and flex-flow are not neccesary, its just for visual context**/
  display: flex;
  flex-flow: column wrap;
  background: red;
}
#red-container a {
  position: absolute;
  left: 0px;
  top: -6.6em;
  border: solid 1px red;
}

下面是实际代码:https://codepen.io/JS3DX/pen/bGEjZbK?editors=1100。感谢 Calvin Spealman's 博客对这个问题的回答。

【问题讨论】:

  • Nicolas 的帖子来自 2010 年,因此可能已经过时了。此外,正如您在他的演示中看到的那样,他使用 :target' 伪选择器代替了他在帖子中描述的方法,这正是您正在寻找的东西。 MDN:developer.mozilla.org/en-US/docs/Web/CSS/:target

标签: css flexbox anchor pseudo-element


【解决方案1】:

解决了!在目标的样式中放置scroll-margin-top: [px|em|rm] 可以更轻松地解决这个问题。这只是从锚点到锚点链接的自动滚动的边距/制动,所以你只需要确定滚动边距有多远,或者导航菜单的大小(如果它有position: fixed)样式:

#one, #two, #three {
  scroll-margin-top: 1em;
}

【讨论】:

    猜你喜欢
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 2015-01-04
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 2021-11-03
    相关资源
    最近更新 更多