CSS Classes and ID

CSS classes and ID are used to refer to elements. The ID attribute refers to one element on the page, while the class element can be applied to more elements on that page. For example, if we create a new ID called header, it can only be applied once on that page; however if we use a class it can be used as many times as necessary.

ID

Rules

  • Must start with a # symbol
  • Can only contain numbers, letters, underscore and dash ( – )
  • Can only be used once on a page

Example

#Example1 {

width:200px;

height:100px;

background-color:#000;

}

Apply that style to a div or a paragraph and give it the ID attribute with the value Example1 and you should see the results.

Classes

Classes work in the same way as IDs, however to define a class you use the period (or dot).

.text_transform
{
text-transform:uppercase;
}

This style applies to anything with the class text_transform.

WELCOME TO YOUR CSS CLASS TUTORIAL

Styles beginning with a period (or dot) can be applied to any element (p, div, table, etc.).

Classes With Selectors

You can apply a class to certain elements; for example, you might want to apply a style to only paragraph <p> tags.

Syntax

selector.class_name 
{
properties;
}

Example

p.text_transform
{
text-transform:uppercase;
}

If the class text_transform is applied to a <p> element it will transform the text to upper case; however if it is applied to any other element, nothing will happen.

Multiple Classes

You can apply multiple classes to elements. To do this you simply separate each class by a space, as shown below.

Example

.ClassOne

{

}

.ClassTwo

{

}


<div class="ClassOne ClassTwo"></div>

Universal Selector

The universal selector will apply the style to any element. You specify it using the asterisk.

Example

*.bluediv
{
margin-top:10px;
}

Any element with the class bluediv would have a top margin of 10px.