HTML Classes 📌


HTML classes allow web developers to define blueprint and create and modify all elements which are formed from a given blueprint.


Let's talk about the class attribute

The class attribute serves the purpose of linking the html element to the logic (JavaScript) and the style sheet. We can access and modify the elements by referencing the class name defined in the class attribute.

Example

In the following example we have three <div> elements with a class attribute with the value of "animal". All of the three <div> elements will be styled equally according to the .animal style:

   
<div class = "animal">
    <h2>Dog</h2>
    <p>Dogs are good.</p>
</div>

<div class = "animal">
    <h2>Cat</h2>
    <p>Cats are not good.</p>
</div>
   
    
 <style>
    .animal {
        background-color: black;
        color: yellow;
        border: 2px solid white;
        margin: 20px;
        padding: 20px;
    }
 </style>
    
 

Result:

Dog

Dogs are good.

Cat

Cats are not good.

The class attribute can be used on any HTML element. The class name is case sensitive!

Syntax for Classes

To create a class; write a period (.) character, followed by a class name. Then, define the CSS properties within curly braces {}

Multiple Classes

HTML elements can belong to more than one class. To define multiple classes, separate the class names with a space, e.g. << class="mammal oviparous">>. The element will be styled according to all the classes specified.

Example

In the following example, the first <

> element belongs to both the "mammal" class and also to the "oviparous" class, and will get the style from both of the classes:

                
<h3 class = "mammal oviparous"> 
    Platypus 
</h3>
<h3 class = "mammal">
    Dogs
</h3>
<h3 class = "oviparous">
    Frogs
</h3>
   
    
 <style>
    .mammal {
       background-color: black;
       color: yellow;
       padding: 20px;
     } 
     
     .oviparous {
       text-align: center;
     }
 </style>
                 
              

Result:

Platypus

Dogs

Frogs

Same class can be shared by different elements

Example

                
<h1 class = "animal"> 
    Whale
</h1>
<h2 class = "animal">
    Elephant
</h2>
<p class = "animal">
    Fox
</p>
<h5 class = "animal">
    Ant
</h5>
   
    
 <style>
 .animal {
    background-color: black;
    color: yellow;
    padding: 10px;
  } 
 </style>
                 
              

Result:

Whale

Elephant

Fox


Ant

That's all for this lesson, see you next one.