How to style HTML elements tags using class names in CSS?

July 19, 2021 - 2 min read

To style an HTML element tag using class names, you can use the class attribute on the HTML element tag and then assign the name of the class to it.

For example, consider 2 p (paragragh) tags with classname of color-red in HTML like this,

<!-- Paragragh tags-->
<p class="color-red">Hello World!</p>
<p class="color-red">Hello Devs</p>

Now in the CSS stylesheet, we can apply the styles to p HTML tags by writing the name of the class.

To denote that we are using a class name in the CSS stylesheet we need to use the . (dot character) before writing the name of the class.

It can be done like this,

/* Use the "color-red" class name in any HTML element tags
 to get the text colors as red */
.color-red {
  color: red;
}

This will apply a font color of red to the text inside the p (paragraph) HTML element tags.

See the above code live in JSBin.

How is it different from using the id attribute?

  • When using the id attribute to style HTML elements, we need to have a unique name for the id. We cannot reuse or have the same id defined on more than 1 HTML element tag.

  • But when using a class attribute and class names instead of using the id attribute, we can reuse it more than once. In our case, we have used the class name color-red in both of the paragraphs tags and both of the tags got the text color change to red.

That's all 😃!

Feel free to share if you found this useful 😃.