#15 HTML class Attribute

HTML class Attribute used to specify the class for HTML element. It is the most used attribute while developing a website. You can apply this attribute in all HTML tags.

In website multiple element may share the same class.

The class Attribute

The class attribute used to point class name in the style sheet (CSS). You can also use it in JavaScript to manipulate multiple tags with the same class name.

See the following example three <div> has the same class name subject. So element styled equally according to .subject style definition in the head tag.

See the Pen class example by Arpit (@soniarpit) on CodePen.

Class Syntax

In any html tag,

<tagname class="class-name">...</tagname>

In CSS just write dot(.) before class name with no space

.class-name

Multiple Classes

HTML elements may have more then one class.

To define multiple classes, separate the class names with a space

In the following example, the first <h2> element belongs to both the city class and also to the main class, and will get the CSS styles from both of the classes: 

<h2 class="city main">London</h2>
<h2 class="city">Paris</h2>
<h2 class="city">Tokyo</h2>

Different tags Can Share Same Class

Different HTML tags can also point to the same class name.

In the following example, both <h2> and <p> points to the “city” class and will share the same style

<h2 class="city">Paris</h2>
<p class="city">Paris is the capital of France</p>

Hope you enjoyed. Happy coding :)

Previous: #14 HTML Block and Inline Tags

Next: #16 HTML id Attribute