【问题标题】:Pseudo Element Hover and text-decoration伪元素悬停和文本装饰
【发布时间】:2013-07-11 12:19:10
【问题描述】:

给定以下 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

【问题讨论】:

  • 我没有看到红色在锚点上工作,它在跨度上工作,文本装饰来自锚点而不是跨度。您正在寻找的最终结果是什么?在文本上加下划线而不是图标?还是??
  • @Huangism 我不想在图标上加下划线。
  • 你想在 A 链接文本上加下划线吗?
  • @Huangism 是的,在链接文本上加下划线。

标签: css pseudo-class


【解决方案1】:

正如我在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;
}
&lt;a href="#"&gt;&lt;span data-icon="✪"&gt;&lt;/span&gt;A Link&lt;/a&gt;

【讨论】:

  • 行为与 OP 小提琴完全不同。
  • 悬停时整个锚点会移动
  • @Huangism 我不知道提问者到底想要什么,我已经更新了。但我的回答的主要部分是不需要像你一样更改标记,因为它可以使用display:inline-block 修复。
  • 前导或尾随空格用inline-block 修剪,因此您需要额外的横向填充来补偿。还有其他想法吗?
  • @DaviLima 你的意思是伪元素中的空格吗?使用white-space: pre 或pre-wrap 保留空格和制表符。
【解决方案2】:

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

如果下划线仍然保留在 IE 中,请在伪元素上设置 line-height: 1,这样一来,您就得到了

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

【讨论】:

    【解决方案3】:

    让事情变得更简单,把事情分开

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

    【讨论】:

      猜你喜欢
      • 2012-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-16
      • 2017-01-08
      • 2015-04-24
      • 2013-10-21
      • 2015-03-11
      相关资源
      最近更新 更多