如何在悬停时清除 a.class css 中 :before 的文本装饰?

How to clear text-decoration of :before in a.class css on hover?

我使用 Font Awesome 在超链接前放置一个图标。我的超链接有一个 css:

a.cancel {
  font-family: 'Open Sans', sans-serif;
  font-size: 14px;
  font-weight: 600;
  font-style: normal;
  font-stretch: normal;
  line-height: 1.71;
  letter-spacing: normal;
  color: #eb1700;
  text-transform: uppercase;
  text-decoration: none;
}

a.cancel:before {
  font-family: "Font Awesome 5 Pro"; 
  content: "\f057";
  padding: 0 4px 0px 0px;
  font-weight: 300;
}

a.cancel:hover {
  text-decoration: underline;
}

a.cancel:hover:before {
  text-decoration: none;
  color: blue;
}

不幸的是,悬停时我的图标下的文字装饰没有被移除。我该如何解决这个问题?

有很多方法可以解决这个问题,但我通常是这样处理的:

display: inline-block 设置为 link,然后将 float: left 设置为其伪元素。

a.cancel {
  font-family: 'Open Sans', sans-serif;
  font-size: 14px;
  font-weight: 600;
  font-style: normal;
  font-stretch: normal;
  line-height: 1.71;
  letter-spacing: normal;
  color: #eb1700;
  text-transform: uppercase;
  text-decoration: none;
  display: inline-block; /* + */
}

a.cancel:before {
  font-family: "Font Awesome 5 Pro"; 
  content: "\f057";
  padding: 0 4px 0px 0px;
  font-weight: 300;
  float: left; /* + */
}

a.cancel:hover {
  text-decoration: underline;
}

a.cancel:hover:before {
  text-decoration: none; /* You can remove this line */
  color: blue;
}
<a href="#" class="cancel">hello</a>

我在此处猜测您的 HTML。假设您的 A 标签中没有额外的 HTML,简短的回答是:您不能通过 CSS 将文本修饰仅应用于 A 标签的一部分。它是否适用于所有的 A 标签。 :hover 在 A 标签上触发。 :before 并不是真正独立的 DOM 元素。 A:hover 无论您是在 :before 部分还是常规部分,如果这有意义,都会触发。

但是,如果您不介意在 A 标签中添加一点额外的 HTML,您可以将下划线仅应用于该元素:

<a class="cancel" href="http://example.com"><i>http://example.com</i></a>

a.cancel:hover i {
  text-decoration: underline;
}

上面会告诉它只在内部标记中放置下划线,而不是整个 A 标记。您可以使用任何您想要的内联标记,例如 span 等。这可能不是您想要的,但如果没有某种分隔,您不能让 A:hover 仅应用于文本而不应用于:前。都是一个 DOM 元素。如果您在 Chrome(和其他)中检查它,您会看到 ::before inside A 容器。