【发布时间】: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"> </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