首页 > 解决方案 > 仅在 CSS 中使链接的 ::before 部分可点击

问题描述

我网页中的标题也是一个链接到它们自己的链接,出于可访问性的原因,我无法真正改变它。

然而,大多数人想要的 Title只是一个可点击的链接。

所以我的html看起来像

<h2 id="myid"><a href="#myid">Title</a></h2>

还有我的 CSS(到目前为止):

h2 a::before { content: " "; }

但是,我远没有知道下一步该做什么的魔法,我尝试查看这个问题,但我真的不知道如何“拯救”该::before部分免受影响。

标签: csshyperlink

解决方案


这有点棘手,但您可以为字符设置固定宽度,并将伪元素重叠h2::after元素的整个长度减去伪元素的宽度,a::before因此无法单击文本。

值得注意的是,这会降低页面的可用性,因此在使用这种方法时要小心

h2 {
  position: relative;
  display: inline-block;
}

h2::after {
  position: absolute;
  z-index: 1;
  content: "";
  right: 0;
  height: 100%;
  width: calc(100% - 1.25em);
}

h2 a::before {
  content: "";
  display: inline-block;
  border-bottom: 1px dashed yellowgreen;
  width: 1.25em;
}

h2 a {
  text-decoration: none;
  color: inherit;
}
<h2 id="myid"><a href="#myid">Title</a></h2>


推荐阅读