April 20, 2012

When to use CSS classes and when to not?

Question by Dude

When should you add classes to elements and style them using class selectors and when should you instead add a class/id on the parent and use the elements just as is?

Example:

<div class="warning-dialog">
    <h3>This is the title</h3>
    <p>This is the message</p>
</div>

.warning-dialog {}
.warning-dialog h3 {}
.warning-dialog p {}

vs.

<div class="warning-dialog">
    <h3 class="warning-title">This is the title</h3>
    <p class="warning-message">This is the message</p>
</div>

.warning-dialog {}
.warning-title {}
.warning-message {}

Or should you do

.warning-dialog .warning-dialog {}
.warning-dialog .warning-title {}
.warning-dialog .warning-message {}

Answer by Madara Uchiha

Ask yourself this simple question:

Do all <x> elements under this common ancestor mean the same thing?

If the answer to that is yes, then you don’t need a class name on those elements. Taking your code as an example, the following is sufficient:

<div class="warning-dialog">
    <h3>This is the title</h3>
    <p>This is the message</p>
</div>

Because inside of a .warning-dialog, all h3 elements (1) and all p elements (1) would mean the same, the title and the content of the dialog! Meaning, you don’t need to have any specific class names on them and they are easily accessible via .warning-dialog h3 or .warning-dialog p.

If however, the answer to above question is “No”, that’s a whole different story:

<div>Warning</div>
<div>Info</div>
<div>Error</div>

You can’t (easily) designate each div with a CSS, they don’t all mean the same thing, so you need to use class names to make it better!

<div class="warning-dialog">Warning</div>
<div class="info-dialog">Info</div>
<div class="error-dialog">Error</div>

Answer by Starx

The base concept is, that

  1. Unique Element to be styled, use id
  2. Collection of similar elements to be styled, use class.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!