我想编写一般的CSS规则集(.bg-parallax),并希望将其应用于多个基于ID的元素。
但为什么需要在CSS选择器中的Class之前添加ID选择器?请看下面的例子:
HTML
<div id="home-cover" class="bg-parallax">
....
</div>
CSS
#home-cover {
}
.bg-parallax {
Does Not Work?
}
#home-cover.bg-parallax {
Works - Why do i need ID selector before Class?
}
答案 0 :(得分:1)
ID和Classes之间的hirarachy是学习CSS和CSS时要学习的一些最重要的问题。 CSS3。
简而言之,让我们通过一个例子来解释它。假设你要买车。汽车可以有一个类似于CSS类的模型(如 - mazda 3)。但是当你去停车场时,有100辆马自达汽车坐在那里。但每个都有一个唯一的序列号 - 这是css中的ID。
关于它的长篇文章在CSS-Tricks.com中:https://css-tricks.com/the-difference-between-id-and-class/
享受您的阅读!
答案 1 :(得分:1)
了解CSS特异性。 Start here
以下是基本规则:
ID(#id
)的特异性为100
课程(.class
)的特异性为10
HTML元素(div
)的特异性为1
更高的特定选择器将覆盖较低的css属性 特定选择器。
让我们看一个例子:
/* specificity = 100 */
#home-cover {
font-size: 60px;
border: 1px solid white;
padding: 10px;
}
/* specificity = 10 */
.bg-parallax {
/* will work, since #home-cover doesn't have this property */
color: red;
/*will work, same reason as above */
font-style: italic;
/* will NOT work, since a higher specific selector (#home-cover) overrides this property */
font-size: 20px;
/* will NOT work, same reason as above*/
border: 1px solid red;
}
/* specificity = 100 + 10 = 110 */
#home-cover.bg-parallax {
border: 1px solid green;
/* will work since this selector has higher specificity than #home-cover */
}
以下是工作片段:
/* specificity = 100 */
#home-cover {
font-size: 60px;
border: 1px solid white;
padding: 10px;
}
/* specificity = 10 */
.bg-parallax {
/* will work, since #home-cover doesn't have this property */
color: red;
/*will work, same reason as above */
font-style: italic;
/* will NOT work, since a higher specific selector (#home-cover) overrides this property */
font-size: 20px;
/* will NOT work, same reason as above*/
border: 1px solid red;
}
/* specificity = 100 + 10 = 110 */
#home-cover.bg-parallax {
border: 1px solid green;
/* will work since this selector has higher specificity than #home-cover */
}
<div id="home-cover" class="bg-parallax">CSS Specificty</div>