Tutorials Tonight's Logo

CSS CLASS SELECTOR


The CSS classes allow us to define multiple CSS properties for a specific class and when that class is added to any element then all the specified CSS property is reflected in the HTML element.

Classes are defined either in the head section within the style tag or in the external stylesheet.

Once a class is defined it can be used as many times you want to use.


Defining a class

A class defined by a class_name preceded by a dot (".") .

Syntax:

.class_name { property: value; }

Defining class in head section:

.class1{
    background-color: #182C61;
    margin: 10px; /* There should be no space between value and unit */
    font-size: 20px;
}
.class2{
    color: #CAD3C8;
    padding: 25px;
}

Defining classes in external stylesheet.

.class1{
    background-color: #182C61;
    margin: 10px; /* There should be no space between value and unit */
    font-size: 20px;
}
.class2{
    color: #CAD3C8;
    padding: 25px;
}

Adding class to the element

A class is added to an element using class attribute. Like shown below.

<p class="class1">This is a paragraph with single class.</p>

Multiple classes can be added to an element. like shown below.

<p class="class1 class2 class3">This is a paragraph with multiple class.</p>

A working example for CSS class.

<!DOCTYPE html>
<html>
    <head>
        <style>
            .class1{
                background-color: #182C61;
                color: white;
                font-size: 20px;
                padding: 15px;
                width: 100%;
                }
        </style>
    </head>
<body>
    <h2>Learning about CSS classes.</p>
    <p class="class1">This paragraph is added with class1.</p>
    <p class="class1">This paragraph is added with class1.</p>
    <p class="class1">This paragraph is added with class1.</p>
</body>
</html>
▶ Run the code

Output:

This paragraph is added with class1.

This paragraph is added with class1.

This paragraph is added with class1.


Follow Us

Copyright © Tutorials Tonight. All Rights Are Reserved.