The "class" attribute in CSS
HTML has a class attribute that is used by CSS to assign different properties within one block so that it can be assigned to any element. Once assigned a specific class, these elements will have all the properties that are attributed to that particular class.
Why are classes important?
- Using a
classin CSS allows the user to apply the same style to multiple elements without having to repeat blocks of CSS code. - More than one
classcan be assigned to an element, hence they can have multiple styles. - It is easier to change the formatting of a
classas opposed to having to change it for multiple elements - One
classcan be assigned to different types of elements like a paragraph or a heading style and hence create design coherence if need be
How to declare a class
Any class is declared by preceding the class name with a (.). The code below shows how to do this.
Note: A class name is case-sensitive
How to assign a class
Now that we know how to declare a class, we will learn how to assign it to a particular element. The example below shows how to do this.
-
From lines 4 to 8 the
exampleClassis defined and assigned particular properties -
The
exampleClassis assigned to an element in line 12 -
The same type of element is declared on line 13 but it does not have any
classassigned to it
Examples
1. Assigning the same class to multiple elements
2. Assigning multiple classes to the same element
Free Resources