The class attribute
The class attribute specifies one or more classes for an element (element refers to a tag).
This is done in order to then access via CSS a group of elements that have the same class and apply certain properties to it (for example, change the text color, font size, and so on).
There is also an id attribute, which, like the class attribute, allows you to select elements on an HTML page.
The difference between the class attribute and the id attribute is that class selects a group of elements (even if it is given to one element, it can later be given to another), and id selects a unique element (there should be no more elements with such an id on the site page, otherwise there will be a conflict).
How to understand what to give an element - a class or an id? A class is given to those elements that are repeated on the pages of the site (so as not to write the same CSS code several times). Even if you currently have only one element, but you feel that similar elements may appear in the future - give this element a class. If you are sure that such an element is unique - then give it an id. Although there is currently a tendency to give all elements a class and leave the id for JavaScript, it is not generally accepted.
An element can have multiple classes, in which case they should be listed separated by spaces.
Class names must be typed in English letters, numbers, without spaces (a space separates classes from each other, an underscore or a hyphen can be used instead). Classes must not start with a number (this is already possible in HTML5, but will not work in older browsers).
Class names should be given in English (not Russian, just English letters!). Names should be meaningful, reflecting the essence of the class.
Example
Let's set the text color to red for all paragraphs with the class test:
<p class="test">Paragraph with class test.</p>
<p>Control paragraph without class.</p>
.test {
color: red;
}
:
Example . Multiple classes for an element
And here let's give the first paragraph several classes - test1 and test2 (we'll write them separated by a space). The test1 class sets the red color of the text, and the test2 class sets the font size to 20px. The second paragraph is given only the class test1 (this paragraph will be red), and the third paragraph is given the class test2 (this paragraph will have a font size of 20px). The first paragraph, which has two classes, will have both the color red and the font size of 20px:
<p class="test1 test2">Paragraph with two classes test1 and test2.</p>
<p class="test1">Paragraph with class test1.</p>
<p class="test2">Paragraph with class test2.</p>
<p>Control paragraph without classes.</p>
.test1 {
color: red;
}
.test2 {
font-size: 20px;
}
:
See also
-
attribute
id,
which sets unique identifiers for elements