Understanding The “C” in CSS

April 22nd, 2008  |  Published in Notebook  |  4 Comments

Understanding how CSS Cascades is very simple… but it’s tricky at first, and I find it’s something I end up explaining to many people as a FED consultant.

**Generally** speaking, the lower down a selector is in a stylesheet, the more weight it gets, and it will override anything that was listed before it…

But what most people don’t know (or forget often…) is…

If you’re redefining something, the way you write your new CSS selector should be at least as specific as the one that was previously defined.

Examples:

You have a div defined as #header with a list of links, and then you define all links nested in list items on a page.


#header li a { color: red; }
li a { color: blue; }

The anchor tags in #header would remain red.. since what you defined was not specific enough, but other links on the page would inherit the blue color.

And if you had a list nested inside of #header with a class of “menu”….


#header li a { color: red; }
.menu a { color: blue; }

They would sill remain colored red, because you didn’t make them as specific as the pre-defined links.

The correct way to recolor the links is displayed below:


#header li a { color: red; }
#header .menu li a { color: blue; }

I hope this wasn’t confusing.. If it was.. post questions below and I’ll try to answer them swiftly.

Responses

  1. drew says:

    May 8th, 2008at 7:55 pm(#)

    Good stuff K… Wasn’t confusing at all. I look forward to reading some more intermediate/advanced techniques in the future. Keep em’ coming!

  2. TrippMD says:

    May 13th, 2008at 10:04 am(#)

    Thanks for the information. I have always gotten confused writting CSS. Hopefully, I can one day create something nice for my site.

  3. tagnu says:

    May 18th, 2008at 7:01 pm(#)

    Good article. May be you could just highlight “redefining” in the following text.

    “If you’re redefining something, the way you write your new CSS selector should be at least as specific as the one that was previously defined.”

  4. Jessica Rae says:

    June 20th, 2008at 10:48 am(#)

    I am a silly girl. I liked randomly finding this, and being all ‘hey, I actually know what CSS stylesheets are and have done a few so I kinda get this!’ Thank you for being you in a universe of too many ‘thems’.

Leave a Response