<div style="color: red;"></div>
#myDiv {
color: blue;
}
.myClass {
color: green;
}
a:hover {
color: orange;
}
p {
color: black;
}
!important
gives a style the highest specificity, but it should be avoided as it makes styles less predictable and harder to maintain.p {
color: gray !important;
}
If selectors have the same specificity, the order in which they appear in the CSS file (or within a <style>
block) matters. If two rules have the same specificity, the browser applies the last declaration.
Selector Type | Example Code | Specificity |
---|---|---|
Inline Styles | <div style="color: red;"></div> |
1000 |
ID Selectors | #myDiv { color: blue; } |
100 |
Class Selectors | .myClass { color: green; } |
10 |
Element Selectors | p { color: black; } |
1 |
Attribute Selectors | [type="submit"] { background-color: blue; } |
10 |
Pseudo-classes | a:hover { color: orange; } |
10 |
Pseudo-elements | p::first-line { font-weight: bold; } |
100 |
Universal Selector | * { margin: 0; padding: 0; } |
0 |
Combinators | h1 + p { font-style: italic; } |
0 |
Negation Pseudo-class | p:not(.special) { color: gray; } |
10 |
Adjacent sibling combinator | h2 ~ p { margin-top: 20px; } |
0 |
General sibling combinator | h2 ~ p { margin-top: 20px; } |
0 |