CSS Class and CSS ID



CSS Tutorial  >  CSS Class and CSS ID

As mentioned in the CSS Syntax page, both class and ID are user-defined selectors.

Class

Class is specified by including a period (.) before the selector name. The syntax for declaring a Class selector is as follows:

.[Class Name] {
  property:value;
  ...
}

For example,

.navbar {
color:#0000FF;
}

To apply this style to the HTML, using the following code:

<p class="navbar">This is a sample using a Class selector.</p>

The above HTML code renders:

We can also specify different instances of a class selector. This is achieved by using the following syntax:

[Type Selector].[Class Name] {
  property:value;
  ...
}

For example, if we have the following CSS declaration,

b.special {
  color:#0000FF;
}

i.special {
  color:#FF0000;
}

The following HTML,

This shows how <b class="special">different instances</b> of a selector <i class="special">can be specified</i>.

would render,

This shows how different instances of a selector can be specified.

Multiple Classes

It is possible to include multiple classes at the same time. For example, assuming we have the following CSS declaration,

.applylarge {
  font-size:20px;
}

.applyred {
  color:#FF0000;
}

the following HTML,

<p class="applylarge applyred">This is an example of multiple classes.</p>

would render,

This is an example of multiple classes.

ID

ID is specified by including a number sign (#) before the selector name. The syntax for declaring an ID selector is as follows:

#[ID Name] {
  property:value;
  ...
}

For example,

#footer {
color:#FF00FF;
}

To apply this style to the HTML, using the following code:

<p id="footer">This is a sample using an ID selector.</p>

The above HTML code renders:

Class vs ID

The difference between ID and class is that an ID selector can be called only once in a document, while a class selector can be called multiple times in a document. The second difference is that ID can be called by Javascript's getElementByID function.

There is no hard rule on when to use ID and when to use Class. My suggestion is to use class as much as possible for maximum flexibility, with the only exception being when you want to use Javascript's getElementByID function, in which case you need use ID.

Class and ID names are both case sensitive. For example, .classone and .ClassOne are two different classes.

Next: CSS Div and CSS Span




Copyright © 2014   1keydata.com   All Rights Reserved   Privacy Policy