Home / Articles / Programming languages / Markup languages / HTML & CSS / When to use CSS ids and when CSS classes instead?

When to use CSS ids and when CSS classes instead?

When to use CSS ids and when CSS classes instead?
When to use CSS ids and when CSS classes instead?
  • Currently 4.5 out of 5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Rating: 4.5/5 (3 votes cast)

Thank you for rating!

You have already rated this page, you can only rate it once!

Your rating has been changed, thanks for rating!

Log in or create a user account to rate this page.

At first glance, the use of classes and ids is almost identical: both can assign CSS properties with needed values to change the appearance of HTML document. But, under what circumstances can we make better use of classes, and under what ids?

The most important rule of using classes and identifiers is that the identifier can only be used once in a document, because it works only with one element. If assigned to an element this unique identifier can no longer be used in the same document.

Classes, on contrary, can be used in a document any number of times. Therefore, if multiple elements have the same properties on the same page, use of the classes can be considered as an ideal solution.

Any element can be assigned a class and id simultaneously. As an example of such an element, let's take all located on the page text boxes, to address them in JavaScript each field also has to be assigned a unique identifier. There is no need to assign any styles for this element.

As a rule, identifier is assigned to the most important elements that have an essential role in shaping the structure of the document. Thus, the more common identifiers are: header, content, nav and footer. Below is code example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-GB" lang="en-GB">
    <title>Simple site</title>
    <meta name="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" type="text/css" href="styles.css" />
    <div id="header"> ... </div>
    <div id="content">
      ... the content of the page ...
    <div id="nav"> ... </div>
    <div id="footer"> ... </div>

Read also

Conditional comments for IE

Conditional comments for IE

How to write in HTML

How to write in HTML

Log in or create a user account to post a comment.


Quick navigation

General navigation