CSS内联样式忽略悬停效果 [英] CSS inline styling ignores hover effect

查看:166
本文介绍了CSS内联样式忽略悬停效果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在玩CSS,发现一个有趣的场景,对此我找不到真正的解释.也许你们中的一些人对此有答案.

I was just playing around with CSS and noticed an interesting scenario for which I couldn't really find an explanation. Maybe some of you have the answer for this.

我有一个带有内联样式的div元素

I have a div element with an inline styling

<div id="text-sample" style="overflow:hidden;">This is a sample text to test the CSS behavior of inline styling</div>

我的CSS

#text-sample {
    width:200px;
    white-space: nowrap;
}

#text-sample:hover {
    overflow:visible
}

此处悬停效果不适用.也就是说,overflow: visible规则不起作用.

Here the hover effect is not applying. That is, the overflow: visible rule is not taking.

注意:将内嵌样式中的overflow:hidden移走将解决此问题.

Note: Moving the overflow:hidden from inline style will fix the issue.

我正在寻找未应用悬停效果的原因.谁能解释这种情况?

I'm looking for the reason why hover effect is not applying. Can anyone explain this scenario?

推荐答案

在CSS中,有一个叫做特异性.简而言之,类似

In CSS, there's something called Specificity. Simply said, something like

#id { color: red; }

将优先于类似的东西

.blue { color: red; }

当具有类似<div id="id" class="blue">的内容时.请参见下面的示例. 这是因为ID选择器(#)被解释为比类更重要.以同样的方式,具有更高声明(在文件中更晚)的同等选择器将具有优先权,并且选择器越具体,它就越重要.

when having something like <div id="id" class="blue">. See example below. This is because an ID selector (#) is interpreted as more important than a class. In the same manner, an equally specific selector with a later declaration (later in the file) takes precedence and the more specific your selector gets, the more important it is.

以您的示例为例:内联样式优先于CSS文件中编写的所有内容(除非使用!important).我相信:hover不会改变这一事实.

For your example: An inline-style takes precedence over anything written in a CSS file (unless using !important). I believe the :hover does not change anything on that fact.

有关详细规则,请参见上面的链接.

For the detailed rules look my link above.

div {
    width:200px;
    white-space: nowrap;
}

#text-sample:hover,
#sample-2:hover {
    overflow:visible;
}

#sample-2 {
  overflow: hidden;
}

#foo {
  color: red;
}

.blue {
  color: blue;
}

<div id="text-sample" style="overflow:hidden;">This is a sample text to test the CSS behavior of inline styling</div>

<div id="sample-2">This is a sample text to test the CSS behavior of inline styling</div>

<div id="foo" class="blue">foo</div>

编辑

如评论中所述,特异性不适用于嵌入式样式.尽管如此,内联样式仍优先于文件中CSS声明中的任何内容.但是,只要将规则移到同一个CSS文件中(正如您提到的那样,),:hover就比另一个规则更重要,因为它在您悬停的那一刻更加具体.

As mentioned in comments, Specificity does not apply to inline styles. Nevertheless, inline styles are taking precedence over anything in a CSS declarations in files. However, as soon as you move the rule into the same CSS file (as you mentioned will work), the :hover is more important than the other rule since it is more specific in the moment you're hovering.

这篇关于CSS内联样式忽略悬停效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆