ID’s and Classes in CSS

In CSS, you can create your own selectors via ID or CLASS. This is how you apply positioning on certain divs to create the layout of your page. This will also say that a certain area on your page should have a background color that is different from the rest. These are very useful and you cannot create a website without them.

# and .

First off, the syntax. The ID selector is preceded by the hash character (#) while the class selector is a full stop (.).

#branding { .... }
.ads { ... }

And in your HTML you would apply them like this:

<div id=&quot;branding&quot;>...</div>
<div class=&quot;ads&quot;>...</div>

Simple enough so far.

One major difference between the two

The ID selector can only be used once in the same HTML document while the class selector may be used multiple times.

Because of that difference, you will notice that in most cases, web designers tend to use the ID selectors for main sections within the site like the header, navigation, content, sidebar and footer.

Difference important for Javascript

If you apply Javascript on your site you MUST follow the rule of only one ID per page otherwise the getElementById function won’t be dependable.

Special functionality

When you create anchors on your page to help you scroll more easily within the document, you use the hash character in the link. Since the ID selector uses that hash character, this mean that you can have a

in your HTML and get the browser to go directly there with http://www.domain.com#comments. The browser with scroll through the page and find the element matching it. A great reason to use ID’s only once.

Elements can have both

<div id=&quot;branding&quot; class=&quot;logo&quot;>...</div>

This could be very useful in instances where you want to apply a certain style only on a certain page. Let’s say you have a gray box at the top of every page explaining what the page is about but on a certain page you want to draw attention it, so you create a class with a red background instead.

Elements can have 2 classes

That’s right! You can apply 2 classes in the same element. Reasons for doing this are basically the same as using an ID and a class in the same element.

<span class=&quot;topbox gray&quot;>...</span>

You cannot have 2 id’s in one element

3 Comments on "ID’s and Classes in CSS"

  1. Ryan Hartkopf says:

    ID’s can act as anchors as well?
    Why didn’t anyone tell me this before?

  2. Enlargement says:

    I am amazed with it. It is a good thing for my research. Thanks

  3. Alex says:

    Elements can have more classes, not only two.

    here the reference:
    http://www.w3.org/TR/html401/struct/global.html#adef-class

Got something to say? Go for it!