2017-06-20 156 views
0

我只是在玩CSS,注意到一个有趣的场景,我无法找到解释。也许你们中的一些人有这个答案。CSS内联样式忽略悬停效果

我有一个div元素与内嵌样式

<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规则没有采取。

注意:移动溢出:隐藏内联样式将解决问题。

我正在寻找悬停效果不适用的原因。任何人都可以解释这个场景

+1

检查控制台是否触发悬停;检查css属性是否被覆盖。 –

+0

尝试更改宽度&nowrap悬停也! – Alex

回答

1

其他所有相同,内联样式优先于通过样式表规则应用的样式。在你的情况下,当悬停时,通过样式表规则调用overflow: visible,但不能覆盖内联样式。如有必要,您可以尝试!important

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

 
#text-sample:hover { 
 
    overflow: visible !important; 
 
}
<div id="text-sample" style="overflow:hidden;"> 
 
    This is a sample text to test the CSS behavior of inline styling 
 
</div>

但它会更容易简单地在#text-sample样式规则中指定的,而不是内联给它overflow: hidden

+0

谢谢你解释这个。增加重要的是工作。 – ajeshrkurup

1

您的内联样式将始终覆盖您的外部CSS。 您可以使用!important:hover

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

#text-sample:hover { 
    overflow:visible!important; 
} 
1

内联样式优先于样式表。有两种方法可以更改:使用JavaScript或在样式表中使用!important

#text-sample:hover { 
    overflow:visible !important; 
} 
+0

有但是尽量不要用!重要 –

0

在CSS中,有一些东西叫Specificity。简单地说,像

#id { color: red; } 

有类似<div id="id" class="blue">时会优先于类似

.blue { color: red; } 

。看下面的例子。 这是因为ID选择器(#)被解释为比类更重要。以同样的方式,具有稍后声明(稍后在文件中)的同样具体的选择器优先,选择器越具体,它就越重要。

对于您的示例:内联样式优先于写入CSS文件中的任何内容(除非使用!important)。我相信:hover不会改变任何事实。

有关详细规则,请查看我上面的链接。

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比其他规则更重要,因为它在您悬停的时刻更具体。

+0

内联样式与特异性无关。特定性适用于样式表中的规则。无论是否应用了给定的样式,首先基于它是内嵌的,然后是样式表规则适用于该规则的特定性。这个特殊问题与特异性无关。 – 2017-06-20 06:56:13

+0

@torazaburo我看到了,我不知道这个词不适用。但是,因为内联样式是最具体的,所以我认为这不会改变我的答案的一般结论(内联优先)。 – SVSchmidt

+0

@torazaburo更新我的信息。我认为这应该没问题。 – SVSchmidt