CSS - Class and Id

  »   CSS  »   CSS Tutorial - Class and Id

CSS - Class and Id attributes

To set a class of elements that share the same properties, the attribute with the same name will be used. On the other hand, you can also use elements id to add styles but it has some restriction when using it. Go on reading to find out more.

CSS - class attribute

You can add the class attribute to the HTML tag to one or more elements. Let's take a look at the following example. This is simpler then it sounds:

CSSp.center { text-align:center; }
p.right  { text-align:right;  }

We created the class center the class right attached to all paragraphs elements. We just have to place those tags into the Paragraph tag like this:

HTML<p class="center">Centered paragraph.</p>
<p class="right">Right aligned paragraph.</p>

Let's suppose now that we pretend to style some more HTML tags using the same tag. We will take for example a paragraph a div and a title and use the same CSS class to style them all.

CSSp.red, div.red, h1.red { color:red; }
/* or we can just remove the attachment to a certain element */
.red { color:red; }

Simple note here is that the name of the class has nothing to do with the attribute value. We can name the class whatever we want.

CSS.class_name { color:red; }

And then attache it to your HTML tag

HTML<h1 class="class_name">I am a red title.</h1>
<p class="class_name">I an awesome red paragraph.</p>
<div class="class_name">
  <h3>This title should also be red.</h3>
  <p>All content of this div should be red.</p>
</div>

Some CSS class names remembers

There are some things to keep in mind when naming classes in CSS.

  • Numbers can never be used at the beginning of a class name. You can on the other hand use numbers anywhere else in the name.
  • Try to use descriptive class names to improve code readability.

CSS - Id attribute

Id attribute has mainly the same usage as a class. The only difference when declaring an id in CSS is that instead of a dot (.

CSS#center {
text-align:center;
color:blue;
font-family:"sans serif"
}

Id/Class differences

Although both #id and .class can be used to style an HTML element, we will always try to use classes for styling and leave #id of Javascript usage. On the other hand, for us to have a valid code, several HTML tags can not share the same #id.

But again, this is just a recommendation for usage and nothing bad will happen if from time to time, you will use #id to add some style to a specific element. Just practice a little bit with concepts and when you are ready to go on and read the next chapter.