Specificity and selectors

Specificity

Specificity uses a four-category system to give a CSS selector a value. The selector with the most specific value wins. Each

Specificity High Low
Selector Inline ID Class, pseudo-class, attribute element
Weight 1,0,0,0 0,1,0,0 0,0,1,0 0,0,0,1

Examples:

1
2
3
4
5
nav#nav > li:hover { colour:red; }
Results in 0,1,1,2

li:nth-child(2):hover { color:red; }
Results in 0,0,2,1

Selectors

These can help you add weight to the Specificity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
.myDiv {
padding-top: 50px;
margin-top: -50px;

&.myDiv2 {
padding-top: 150px;
margin-top: -150px;
}
}

/*Resulting CSS and what it would select on

.myDiv { padding-top: 50px; margin-top: -50px; } ~ 0,0,1,0
.myDiv.myDiv2 { padding-top: 150px; margin-top: -150px; } ~ 0,0,2,0

<div class="myDiv myDiv2"></div>
*/

Universal and combinator selectors

These have no effect on specificity.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// universal selector (*) matches elements of any type.

* { box-sizing: border-box; font-family: "Open Sans", sans-serif; }

// The adjacent sibling combinator (+) separates two selectors and matches the second element only if it immediately follows the first element, and both are children of the same parent element. Example: Paragraphs that come immediately after any image

img + p { font-style: bold; }

// The child combinator (>) is placed between two CSS selectors. It matches only those elements matched by the second selector that are the children of elements matched by the first. Example: List items that are children of the "my-things" list

ul.my-things > li { margin: 2em; }

// The general sibling combinator (~) separates two selectors and matches the second element only if it follows the first element (though not necessarily immediately), and both are children of the same parent element. Example: Paragraphs that are siblings of and subsequent to any image

img ~ p { color: red; }

// The descendant combinator — typically represented by a single space ( ) character. Example: List items that are descendants of the "my-things" list

ul.my-things li { margin: 2em; }

pseudo-class

Common pseudo-class selectors

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
&:first-child {
margin-left: -8px;
}

&:hover {
text-decoration: underline;
color: white;
}

&:last-child {
margin-bottom: 28px;
}

&:visited {
color: white;
}

:nth-child(1) {
width: 900px;
}

Attribute Selector

1
.someClass[someAttribute]