简体   繁体   中英

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

I use Font Awesome to put an icon before my hyperlink. I have a css for my hyperlink:

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;
}

Unfortunately, the text-decoration isn't removed under my icon when hovered. How can I fix this?

There are many ways to fix that, but here is how I usually proceed:

Set display: inline-block to the link, then float: left to its pseudo-element.

 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> 

I'm guessing a bit on your HTML here. Assuming there is no additional HTML in your A tag, the short answer is: you can't have the text-decoration apply to only part of the A tag via CSS. It applies to all of the A tag or not. The :hover is triggering on the A tag. The :before isn't truly a separate DOM element. The A:hover is triggering regardless of if you're over the :before portion or the regular portion, if that makes sense.

However, if don't mind adding a little extra HTML inside your A tag, you can have the underline apply only to that element:

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

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

The above will tell it to put the underline only in the internal tag, not the whole A tag. You can use whatever inline tag you want, such as span, etc. This may not be what you want, but without some sort of separation, you can't have the A:hover apply only to the text and not to the :before. It's all one DOM element. If you inspect it in Chrome (and others), you'll see the ::before inside the A container.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM