Element classes in CSS
In previous lessons, we selected page elements by tag name, setting styles for example for all paragraphs at once. However, a page may contain paragraphs of different types, to which different styles need to be applied. To solve this problem, you can assign different paragraphs to different CSS classes.
To assign a tag to a class, you need to write the class attribute to this tag, and in it - the class name you came up with, consisting of letters, numbers, underscores and hyphens.
Let's look at an example. Let's make paragraphs with two types of classes - eee and zzz:
<p class="eee">
paragraph with class eee
</p>
<p class="eee">
paragraph with class eee
</p>
<p class="zzz">
paragraph with class zzz
</p>
<p class="zzz">
paragraph with class zzz
</p>
Now let's go to the paragraphs with different classes in CSS and give them some styles. For example, let's color the paragraphs with class zzz red, and the paragraphs with class eee green.
To do this, we need to access our classes in the CSS file. The syntax for accessing them is as follows: first comes the dot symbol, then comes the class name we came up with. That is, to access the eee class, we need to write .eee, and for the zzz class, we need to write .zzz.
So, let's do what we described. Let's add CSS styles for the classes we entered to our HTML:
.eee {
color: green;
}
.zzz {
color: red;
}
If we run our code, the result will be as follows:
The following code is given:
<ul>
<li class="odd">text</li>
<li class="eve">text</li>
<li class="odd">text</li>
<li class="eve">text</li>
<li class="odd">text</li>
<li class="eve">text</li>
</ul>
Color the elements with class odd red and the elements with class eve green.
The following code is given:
<h2 class="eee">Title</h2>
<p class="eee">
paragraph
</p>
<p class="eee">
paragraph
</p>
<p>
paragraph without class
</p>
<ul class="eee">
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
<li>text</li>
</ul>
Color all elements with class eee red.
Explain why in the previous task the tags li are colored red, although the class that specifies the color is assigned to the tag ul.