Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

css - How element selector is more specific than id selector?

As I understand elements are least specific. (element vs id). Please help me in understanding the specificity of selectors generally.

<div id="container">
    <div id="firstDiv">FIRST Div inside CONTAINER</div>
    <div id="secondDiv">SECOND Div inside CONTAINER</div>
</div>
body{
    width: 780px;
    margin: 20px auto;
}
#container > div:not(:last-of-type){
    margin-bottom: 0px; /*How its more specific than ID selector below? */
}
#container {
    border: 15px solid orange;
    padding: 10px;
}
#firstDiv{
    margin: 50px; /*This is not taking effect*/
    border: 5px solid blueviolet;
}
#secondDiv{
    border: 5px solid brown;    
}

http://jsfiddle.net/t2RRq/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To understand CSS specificity, read The Specificity Wars. There’s a handy reference sheet, too:

So, a selector like #foo would have 1,0,0 specificity, while an element selector like p would have 0,0,1 specificity. Out of these two, the ID selector would “win” as 100 is greater than 1.

A more specific (heh) version which also includes pseudo-elements and pseudo-classes can be found here: http://www.standardista.com/css3/css-specificity/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...