这是我的HTML代码:
<div id="main_image" class="anim_hidden"></div>
和我的css代码:
section#header #main_image {
z-index: 0;
display: block;
position: absolute;
top: -200px;
right: -100px;
width: 546px;
height: 509px;
background: url('../images/iphone.png') no-repeat 0 0 transparent;
}
.anim_hidden {
display: none;
}
以某种方式显示属性未被覆盖。如果我使用:
.anim_hidden {
display: none !important;
}
或
section#header #main_image.anim_hidden {
display: none;
}
我真的需要以这种方式选择元素吗? 我有更多的元素,我需要用类anim_hidden覆盖它。
答案 0 :(得分:1)
特定性是浏览器决定哪个属性的方法 值与元素最相关并且可以应用。 特异性仅基于由组成的匹配规则 选择不同的种类。
还请注意!important
:
在样式声明上使用
!important
规则时,这个 声明覆盖CSS中的任何其他声明,无论在何处 它在声明列表中。虽然,!重要无关 具有特异性。 使用!important
是不好的做法,因为它 因为你破坏了你自然的级联,所以会使调试变得困难 样式表。 强>
CSS选择器的不同组件具有与唯一性程度相关的不同权重,id
被认为比类更重要 - 实际上可以(通常应该)单独使用,即
section#header #main_image
可能是多余的 vs
#main_image
因为文档中只应该有一个带有id
#main_image
的元素(这在使用相同CSS的不同页面的实例中不太相关)。
因此,您可能需要考虑构建规则。目前,初始规则被认为更重要,因为它不仅具有更多的选择器方面,而且具有更大的权重(id
)
或者,您可以使用:not
选择器来转义anim_hidden
实例:
section#header #main_image {
z-index: 0;
display: block;
position: absolute;
top: -200px;
right: -100px;
width: 546px;
height: 509px;
background: url('../images/iphone.png') no-repeat 0 0 transparent;
}
section#header #main_image:not(.anim_hidden) {
display: block;
}
.anim_hidden {
display: none;
}