Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Utilize Selector Specificity to Control Applied Styles


    When selectors conflict, the browser needs to know which property / value combination to paint. Specificity is one of the core concepts of CSS and is important to understand in order to implement deterministic styles. Let's look at the specificity rules and learn the power of each selector.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Instructor: We can target all of our navigation LIs by simply doing LI color blue. As you can see when we refresh, we get them to all be blue. We can add a conflicting style to one LI, the home LI, by giving it a class of home. Now we can target that class by dot home color red. Now when we save and refresh our home LI is now red while all of them are blue.

    When multiple selectors are targeting the same element, the browser needs to know which one to apply. This is where the cascade and specificity come into play. Element selectors have a specificity value of zero zero one, while classes have zero one zero. Because this value is larger than the element, the home class is going to overrule the LI. That's why it's red.

    Now let's give our home LI an ID of home. We'll target that by hashtag home, give it a color of gray. Save and refresh and we see that now our red goes to gray. This is because IDs have an even higher specificity of element and classes of one zero zero. This is going to overrule the other two.

    Even if we added more targeted element selectors to the color red, for example, div UL and LI, the ID still wins. This is because the ID of one zero zero is larger than an element with three elements. As you can see, zero zero three is still smaller.

    Even when we combine elements with classes to target our LI, when we save and refresh, the ID still wins. This would be like having a one three, which is still smaller than the one zero zero of the ID.

    It's also good to know that inline styles will beat out IDs, classes, and elements. Give it a color of purple and refresh. This makes our home LI purple. Then something that even beats inline styles is using the important tag. If we go back and put it onto our element selector and refresh, we're back to blue. That's because an important rules all in this case.