伪元素悬停和文本装饰

时间:2013-07-12 20:40:32

标签: css pseudo-class

给出以下html:

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

是否可以在悬停时更改text-decoration(无)? color会发生变化,而text-decoration则不会。

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 个答案:

答案 0 :(得分:7)

正如我在this other answer中所解释的那样,您可以使用display: inline-block来阻止设置为祖先的text-decoration传播到您的元素:

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>

答案 1 :(得分:0)

让事情变得更容易并将其分开

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

答案 2 :(得分:-1)

使用display: inline-block适用于除IE之外的所有浏览器。要使其在IE8 +中工作,请将overflow:hidden添加到包含图标的伪元素。

如果下划线仍然在IE中,请在伪元素上设置line-height: 1,所以总得到

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