Using ID and Class in CSS

You’ll often find yourself using id’s and classes in CSS.

Their sole purpose is to group elements — in order to apply a common set of styles to them.

The id is used when you wish to apply a style to only one specific element per web page. The class on the other hand is used to apply a style to a set of elements multiple times on a web page.

CSS ID

When styling elements, each id should be unique. To create a id the number sign ( # ) is used. Following this, the styles are applied ( properties and their values ).

Step 1: Declare your ID in style.css

#heading
{
text-decoration: underline;
}
#format
{
color: blue;
}

Step 2: Apply your ID to An Element on Your Web Page

<h3 id="heading"> New2HTML.com </h3>
<p id="format"> Read it. Learn it. Apply it. </p>

CSS Class

A class is used when we wish to apply a style to more than one element. Unlike the id, a single class can be used multiple times on a web page.

To create a class, a dot ( . ) precedes the class name. Following this, the properties and values are specified.

Step 1: Declare your class in style.css

.display
{
   color: purple;
}

Step 2: Apply your class to Elements on your Web Page

<h3 class="display">What is New2HTML? </h3>
<p class="display"> An online resource catering to beginners wanting to create their own website </p>

In the example above the class display was applied to the main heading as well as the paragraph.

Try this out for yourself, you’ll notice both the heading and the paragraph are both displayed in the color purple.