In CSS, is it better to use span.icon or .icon? And for that matter, is it ok to do crazy inheritance stuff like:

body #content p span.icon

Or is it better with just...

span.icon

I am unaware of how to optimize this!

3 answers

Doug 1095
3
points
This was chosen as the best answer

Use the simplest selector that gets the job done.

As Phil Lindsay wrote, a bare class selector like .icon gets applied to all elements with that class. If you only plan to apply the class to a single kind of element or if you want a style to apply to lots of different elements, this is the way to go. On the other hand, if you plan to use a class on multiple elements, but you only want the style to apply to one, then use a more specific selector like a.icon. This will style links but not other elements, even if they have the same class.

Similarly, if you have elements in different parts of the document that you want to style differently, that's when you have to use more specific selectors, like #menu .icon vs. #header .icon, which will style elements in those sections differently.

Finally, adding more ancestors to your selector changes its specificity, meaning these styles will override other less specific styles. Here's an example:

  .icon {color: red}
  div .icon {color: green}
  body div .icon {color: blue}
  #menu span {color: purple}
  #menu .icon {color: orange}
  body #menu span {color: navy}

Can you guess what color the text will be?

  <div class="icon">
    hello world
  </div>

  <div>
    <span class="icon">
      hello again
    </span>
  </div>

  <div id="menu">
    <span>
      and again
    </span>
  </div>

  <div id="menu">
    <span class="icon">
      once more
    </span>
  </div>

See answer here.

Answered almost 9 years ago by Doug
2
points

On the reverse side of Phil Lindsay's comment, context specific CSS is handy for letting other developers know which styles in your CSS are only for specific tags.

For example, this: img.linked {border: 0 px;} is fairly generic, it'd probably be better to name it .nb for quickly slapping on any tag you want to remove the border from.

But look at: img.avatar {margin:5px; border:solid black 1px;}
If I had never seen your CSS file before, and I read this tag, I would know it's meant to be used solely on images.

Just a thought, hope this helps!

Answered almost 9 years ago by Preston Badeer
0
points

The main benefit of using .icon instead of span.icon is that you wouldn't be limited to just applying the icon class to span elements. If you specified it as .icon you would have the flexibility of applying it to other elements e.g. strong, em, a, etc.

Answered almost 9 years ago by Phil Lindsay