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 */
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
When using the
idattribute to style HTML elements, we need to have a unique name for the
id. We cannot reuse or have the same
iddefined on more than 1 HTML element tag.
But when using a
classattribute and class names instead of using the
idattribute, we can reuse it more than once. In our case, we have used the class name
color-redin both of the paragraphs tags and both of the tags got the text color change to
That's all 😃!