Jenthe
Jenthe

Reputation: 797

Using CSS selector specifity over selector ID's?

In class we are teached to avoid creating ID's in your HTML so you can use them to identify that element in your CSS file. Instead we must use selector specifity as much as possible.

Take for example this simple HTML:

<body>
  <div>
     <div>
       <div>
          The div you want to style.
       </div>
     </div>
  </div>
</body>

Is it better to use this:

body > div > div > div{
     color: blue;
}

or give the element an id (let's take 'middle') and use this:

#middle{
     color: blue;
}

What are the differences (if any at all) performance and usability wise?

Upvotes: 1

Views: 146

Answers (3)

Timidfriendly
Timidfriendly

Reputation: 3284

The difference in speed between IDs and Classes in modern browsers is so negligible in real world situations it is really not an issue. Therefore current main-line thinking is to use classes where extra clarity and specifity is needed. This way you avoid specifity wars and balances maintainability with code purity.

<body>
  <div>
     <div class="more-specific-if-needed">
       <div class="middle">
          The div you want to style.
       </div>
     </div>
  </div>
</body>

.make-more-specific-if-needed .middle {
    /* cool styles */
}

Or even use chained selectors to gain extra specifity. You could then split styles in to separate structure based build styles and appearance based theme styles.

<body>
  <div>
     <div>
       <div class="semantic-role theme">
          The div you want to style.
       </div>
     </div>
  </div>
</body>

.semantic-role.theme {
    /* cool styles */
}

For further reading:

Upvotes: 2

Billy Moon
Billy Moon

Reputation: 58531

Much better to use ID. Performance difference is minimal, and not the important point. I think code readability / maintainability is more important.

One advantage of using ID, is that you could move your element to a different part of the page, and it would retain it's style rules - without counting the containing elements.

Upvotes: 1

Christian-G
Christian-G

Reputation: 2361

Performance wise it's fastest to get an element by its id than it is to traverse the dom.

From a usability point of view I would be careful using too many id's since they can be only used once for an element.

So it's a question of what you think is more important and how many items we are talking about. Is the speed gain worth the losing of re-usability

Upvotes: 1

Related Questions