Obvious In Hindsight
Archive of tips, tricks and solutions for designers and programmers!

CSS: ID vs. Class

IDs and classes are used as part of a HTML element to trigger (call on)  the styling in your CSS documents.

What’s the difference?

An ID can only be called on once and is used for a unique element of your web page such as a banner, navigation menu or footer. The following example demonstrates how a div is defined using an ID (#).

div#header { background-color: black; }

Similarily, sub-elements of the above div can be defined as follows (notice that the sub-element is placed after the id name – this paragraph element does not need to have an id defined in html as your style sheet will automatically trigger it):

#header p {color:#F00;}

A class, as the name implies, can be called on more than once and can therefore used more than once on elements such as paragraphs, headers or links. The following example demonstrates how a paragraph is defined using an class (.).

div.content-box{ width:300px;  }

Similarily, sub-elements of the above div can be defined as follows (again, notice that the sub-element is placed after the class name – this paragraph element does not need to have a class defined in html as your style sheet will automatically trigger it):

.content-box p{color:#900;}

The benefit of styling sub-elements

Simply put, by not having to define class=”somename” or id=”somename” in your elements you are minimizing the amount of code in your overall HTML document. The less clutter the better.

Everything’s obvious in hindsight, eh?

No Responses to “CSS: ID vs. Class”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.