html - 如何通过悬停摆脱 <a> 标签内 <span> 上的下划线?

标签 html css anchor text-decorations

fiddle

HTML

<ul>
    <li><a href="#">Messages<span>1</span></a></li>
</ul>

CSS

a {
    text-decoration: none;
}

a:hover {
    text-decoration: underline;
}

a:hover span {
    text-decoration: none;
}

span {
    background-color: red;
    border-radius: 999px;
    color: white;
    margin-left: 2px;
    position: relative;
    top: -.5em;
    font-size: .75em;
    font-weight: bold;
    padding: 0 .3em;
}

当您将鼠标悬停在链接上时,下划线将应用于 <span>即使我设置了 text-decoration: none .有办法摆脱它吗?

最佳答案

尝试更改 display<span>inline-block如下:

Example Here

span {
    background-color: red;
    border-radius: 999px;
    color: white;
    margin-left: 2px;
    position: relative;
    top: -.5em;
    font-size: .75em;
    font-weight: bold;
    padding: 0 .3em;
    display: inline-block; /* <-- Added declaration */
}

解释

根据 CSS level 2 specification , text-decoration不会传播到嵌套原子内联级元素的内容 - 例如内联 block 和内联表。

16.3.1 Underlining, overlining, striking, and blinking: the 'text-decoration' property

[...] Note that text decorations are not propagated to floating and absolutely positioned descendants, nor to the contents of atomic inline-level descendants such as inline blocks and inline tables.

还有规范说明(我的重点):

Underlines, overlines, and line-throughs are applied only to text (including white space, letter spacing, and word spacing): margins, borders, and padding are skipped. User agents must not render these text decorations on content that is not text. For example, images and inline blocks must not be underlined.

另请注意,文本装饰会粘附在文本本身上,因此:

Relatively positioning a descendant moves all text decorations affecting it along with the descendant's text; it does not affect calculation of the decoration's initial position on that line.

关于html - 如何通过悬停摆脱 <a> 标签内 <span> 上的下划线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27137967/

相关文章:

javascript - 阿拉伯文字不显示,但字符 الÙ...Ù...Ù„Ù 显示

javascript - 动态在标题中创建网站顶部通知栏

javascript - anchor 标记不工作 Chrome 扩展

html - 如何使 anchor 标记内的图像可访问?

javascript - 为什么 fullpage.js 的部分大于窗口?

CSS 过渡闪烁 :visited in Safari, Chrome 和 Firefox,但不是 Opera

javascript - 悬停链接时添加背景图像

html - 如何根据文本量缩小某些文本上方的图像?

html - 如何解决溢出问题(只是 overflow-y 可见)?

javascript - 使文本在看起来像 iPhone 表单的 html 页面中可选择