HTML Classes

The class Attribute

The class attribute in HTML defines one or more classes for an element.

Multiple HTML elements can share the same class. And An HTML Element can contain multiple classes.

Example

Run Code
<!DOCTYPE html>
<html>
    <head>
        <style>
            .city {
                background-color: tomato;
                color: white;
                border: 2px solid black;
                margin: 20px;
                padding: 20px;
            }
        </style>
    </head>
    <body>

        <div class="city">
        <h2>London</h2>
        <p>London is the capital of England.</p>
        </div>

    </body>
</html>

The Syntax For Class

In the <style> element as well as in a .css file, to apply styles to a class, you need to add a dot (.) before the class name.

Example

Run Code
<h2 class="city">London</h2>
<p>London is the capital of England.</p>

Use of the class Attribute in JavaScript