In this series, we will have some CSS interview questions that cover the main concepts of CSS
01
We have this div element in our HTML
<div id="div" class="div"></div>
And, we have these styles in our CSS file
div.div {
background-color: red;
}
#div {
background-color: blue;
}
.div {
background-color: yellow;
}
div {
background-color: white;
}
Which background color will be applied to this div? And, why?
Each selector has a fixed number.
Id (starts with #) => 100
Class (starts with .) => 10
Attribute selectors (like [dir="rtl"]) => 10
Seudo classes (like :hover, :focus, :nth=of-type, ...) => 10
Element (div, p, ...etc) => 1
Seudo element (like ::before, ::after, and ::placeholder) => 1
Therefore, in the above example, it's blue because the highest-matched selector is the ID with a value of 100.
Notes
- Each of the above CSS selectors has a specificity value.
- CSS first looks for all matched selectors, then it calculates their specificities, and then decides which one will be applied.
- By default, when specificities are equal, CSS will take the last selector, as it overrides the previous one.
- Inline styles have more priority than external selectors.
- The
!important
keyword overrides all other styles, even inline styles.
Quiz
What if we remove the ID selector from our CSS file? Which color will be applied in this case? And, why?
div.div {
background-color: red;
}
.div {
background-color: yellow;
}
div {
background-color: white;
}
Thanks for reading.
Top comments (0)