4

Given the following html:

<a href="#"><span data-icon="✪"></span>A Link</a>

Is it possible to change the text-decoration (to none) on hover? The color will change, the text-decoration will not.

CSS:

a { text-decoration: none; }
a:hover{ text-decoration: underline; }
a:hover [data-icon]:before{
  /*Doesn't work*/
  text-decoration: none;

  /*Works*/
  color: red;
}

jsfiddle

3 Answers3

11

As I explained in this other answer, you can use display: inline-block to prevent text-decoration set to an ancestor from propagating to your element:

a {
  text-decoration: none;
}
a:hover {
  text-decoration: underline;
}
a > [data-icon]:before {
  display: inline-block; /* Avoid text-decoration propagation from `a` */
  content: attr(data-icon);
}
a:hover > [data-icon]:before {
  color: red;
}
<a href="#"><span data-icon="✪"></span>A Link</a>
Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • the behavior is completely different than the OP fiddle. – Huangism Jul 12 '13 at 20:49
  • the whole anchor shifts when you hover – Huangism Jul 12 '13 at 20:56
  • @Huangism I didn't know exactly what the asker wanted, I have updated it. But the main part of my answer is that there's no need to change markup, like you do, because it can be fixed using `display:inline-block`. – Oriol Jul 12 '13 at 20:58
  • Leading or trailing whitespace is trimmed with `inline-block`, so you'll need extra lateral padding to compensate. Any other ideas? – Davi Lima Nov 29 '15 at 13:39
  • 1
    @DaviLima Do you mean whitespace in the pseudo-element? Use `white-space: pre` or `pre-wrap` to preserve spaces and tabs. – Oriol Nov 29 '15 at 13:49
  • @Oriol: worked like a charm, thank you. Much more elegant than using padding ;) Just to clarify, pre-wrap didn't work because it generated duplicate spaces before my `" - "` pseudo-element (it's a horizontal items separator) and none afterwards. `pre` did the trick. – Davi Lima Nov 29 '15 at 14:06
0

Make things easier and separate it out

http://jsfiddle.net/nyFxn/2/

<a href="#"><span data-icon="✪"></span><span class="text">A Link</span></a>

CSS

a:hover{  text-decoration: none; }
a:hover [data-icon] {

  /*Works*/
  color: red;
}
a:hover .text {
    text-decoration: underline;
}
Huangism
  • 16,278
  • 7
  • 48
  • 74
-1

Using display: inline-block works in all browsers but IE. To get it to work in IE8+, add overflow:hidden to the pseudo element containing the icon.

If the underline still remains in IE, set line-height: 1 on the pseudo element, so in total you get

a [data-icon]:before {
    display: inline-block;
    overflow: hidden;
    line-height: 1;
}