Space is Critical in CSS Selectors

If you are having difficulty getting a particular CSS style to “appear”, one thing to look at is your selector. A tiny space can cause two different selections if you are not careful.

For example, notice the single space difference between these two selectors:

div#navbar {
    background-color: #999;
}
div #navbar {
    background-color: #333;
}

That presence or lack of a single space between the (div) element and the class selection symbol (#) causes two different selections to occur. No space means the style will apply to (div) elements which are themselves marked with the class navbar. A single space means the style will apply to elements within the (div) element which themselves are marked with the class navbar.

For example,

div#navbar {
    background-color: blue;
}

would make this entire div’s background blue:

<div class="navbar">
  <p>item</p>
  <p>item</p>
</div>

However, this:

div #navbar {
    background-color: blue;
}

would not apply the style. That critical space indicates a descendant element selector. It is expecting the inner (p) elements to have the navbar class. Since those (p) elements do not have navbar classes, you would see nothing and probably wonder why “it is not working”.

The descendant selector can be useful sometimes, but know the difference of what happens if that space appears in that critical spot so you don’t pull your hair out in frustration. If your style is not appearing, check for this easy space mistake.

Nerd Aside: The # symbol goes by many names around the world, such as pound sign, number sign, hash, hatch, tic-tac-toe, gate, crunch, or my favorite octothorpe. Mmm, octothorpe!

  • Share/Bookmark




Leave a Reply