When there are contradicting styles in your project, the css interpreter chooses the styles which were defined with higher specificity. For example, when Bootstrap sets the background-color of the body, and you therefore can’t easily set the body background color.
If there is a tie, then the compiler overrides the prior style, so whichever was executed last breaks the tie.
- !important overrides other specificities.
- A = number of matching ID selectors
- B = number of class selectors, attributes selectors, and pseudo-classes
- C = count the number of type selectors and pseudo-elements
- ignore the universal selector
Examples:
- What color background will the element have?
<div class="one two three four">Hi</div>.one .two .three {
background-color: purple;
}.four {
background-color: green;
}
2. What color will the background have?
<div class="one two three four">Hi</div>.one .two .three {
background-color: purple;
}.four {
background-color: green !important;
}
3. What color will the background have?
<div class="one two three" id="four">Hi</div>.one .two .three {
background-color: purple;
}#four {
background-color: green;
}
4. What color will the background be?
<div class="one two">Hi</div>.one {
background-color: red;
}.two {
background-color: orange;
}
5. What color will the body be? (tricky)
// In the head we are importing bootstrap: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>body {
background-color: green;
}
6.
<p class="one">Hi</p>.one {
background-color: red;
}p {
background-color: orange;
}
Answers:
- purple
- green
- green
- orange
- white
- red