Quick CSS Quiz #4

Abdelrahman Ismail on October 11, 2018

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. ... [Read Full]
markdown guide
 

Just to add some salt: remember that css reads from right to left. It means that the browser will parse it:

  • take element with ID "happy" (none element)
  • invert selection (all elements)
  • find which has any parent with class "wrapper"

You can see that with a large DOM it can be really expensive. If you need performance (big app with lots of animations), never use ":not".

 

I wasn't aware of performance implications for using :not, but it makes sense now.

What if you use :not with a specific selector, is it still expensive?
For instance,
#toybox .teddy-bear:not('.blue')

I would expect this first selects all teddy bears inside the toybox, and then filters out the teddy bears that are blue. That makes sense, doesn't it?

But if it worked in reverse, looking through the entire DOM house for objects that are not blue, and then filtering for not blue objects that are teddy bears inside the toybox, it would be expensive indeed.

 

I'm not a Chrome engineer, but there's a lot of article about rendering online.

Human read CSS form left-to-right because it makes sense in our world (I need to open the toybox first to search for teddy-bear). But browsers do the opposite.

In practice (recent browser and computer), it need a huge DOM for this to matter. Keep your CSS clarity first, then think about perfs. Again, CSS is a pain to maintain, write it as clear as possible !

 

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 using important 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.

 

i really like these Quick CSS quiz, i may start adding some my self.

 
 

I got it because I understand specificity. It's a good interview brainteaser though. I might use it myself.

code of conduct - report abuse