In this series, I try to focus on CSS weird parts, throw quiz and its answer, hoping to give a better understanding of how CSS works in depth.
The problem:
<div class="wrapper">
<h1 id="header" class="is-red">Red text</h1>
<span id="span" class="is-blue">Blue text</span>
<p id="text" class="is-green">Green text</p>
</div>
#header.is-red {
color: red;
}
span.is-blue {
color: blue;
}
.is-green {
color: green;
}
The previous code snippets, for three different HTML elements wrapped in a div .wrapper
, each element has a different color as specified in the style snippet, if you added the following CSS code at the end of the stylesheet what will be the color for header, span, and paragraph elements?
.wrapper :not(#happy) {
color: black;
}
Options:
- header is red, span is blue, and paragraph is green
- header is red, span is blue, and paragraph is black
- header is red, span is black, and paragraph is black
- all elements are black
The answer:
you can find the answer below, but please give yourself a couple of minutes to think about it, to make sure you benefit from this quiz.
The correct answer is: all elements are black
If you wonder why this is the correct answer, please read the discussions below..
You can find this challenge very easy this time, if you know how "CSS Specificity" works, but I want to mention here that you can use
:not
pseudo-class with a fake id to increase selector specificity, rather than usingimportant
keyword.Let's calculate each selector's specificity:
a-
#header.is-red
(1-1-0)b-
span.is-blue
(0-1-1)c-
.is-green
(0-0-1)And the rule-set selector's specificity is (1-1-0), which is greater than a and b selectors and equal to c, but it comes last in the stylesheet; so its declaration will apply over the all three selectors, and all elements will have a black color.