HTML Class Attribute
HTML class attribute is an essential feature that allows developers to add styles to HTML elements using CSS. It is used to define a class name for an element, which is a word or a group of words that can be used to identify the element and apply specific styles to it.
Syntax
The syntax for the HTML class attribute is as follows:
1<element class="class-name">
Where element
can be any HTML element like div
, p
, span
, h1
, etc. and class-name
can be any string that does not contain spaces.
Using the Class Attribute
Here are some examples of how to use the class attribute in HTML:
Example 1: Adding Class to a Paragraph Element
1<p class="my-class">This is a paragraph with a class applied to it.</p>
In this example, the paragraph element is given a class name of "my-class" using the class
attribute. This class name can be used to apply specific styles to this paragraph using CSS.
Example 2: Adding Multiple Classes
1<p class="my-class1 my-class2">This paragraph has multiple classes.</p>
In this example, the paragraph element has two classes applied to it, "my-class1" and "my-class2". This can be useful when you want to apply styles to a group of elements using one or more classes.
Example 3: Using Class with CSS
1<style> 2.my-class { 3 color: red; 4 font-size: 18px; 5 } 6</style> 7 8<p class="my-class">This paragraph has styles applied to it using CSS.</p>
In this example, the style
element is used to define styles for the class named "my-class". The styles will be applied to any element with this class name, as demonstrated in the paragraph element below.