Classes in CSS

Lecture



Classes are used when you need to define a style for an individual element of a web page or specify different styles for a single tag. When used in conjunction with tags, the syntax for the classes will be as follows.

Tag. Class name {property1: value; property 2: value; ...}

Inside the style, first write the desired tag, and then, through a dot, the custom class name. Class names must begin with a Latin character and can contain the hyphen (-) and underscore (_) characters. The use of Russian letters in class names is not allowed. To indicate in HTML code that a tag is used with a particular class, the attribute class = "Class Name" is added to the tag (example 8.1).

Example 8.1. Using classes

<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Классы</title> <style> P { /* Обычный абзац */ text-align: justify; /* Выравнивание текста по ширине */ } P.cite { /* Абзац с классом cite */ color: navy; /* Цвет текста */ margin-left: 20px; /* Отступ слева */ border-left: 1px solid navy; /* Граница слева от текста */ padding-left: 15px; /* Расстояние от линии до текста */ } </style> </head> <body> <p>Для искусственного освещения помещения применяются люминесцентные лампы. Они отличаются высокой световой отдачей, продолжительным сроком службы, малой яркостью светящейся поверхности, близким к естественному спектральным составом излучаемого света, что обеспечивает хорошую цветопередачу.</p> <p class="cite">Для исключения засветки экрана дисплея световыми потоками оконные проемы снабжены светорассеивающими шторами.</p> </body> </html> 

The result of this example is shown in Fig. 8.1.

  Classes in CSS

Fig. 8.1. Type of text decorated using style classes

The first paragraph is justified in width with black text (this color is set by the browser by default), and the next one to which the class named cite is applied is displayed in blue and with a line to the left.

You can also use classes without specifying a tag. The syntax is as follows.

.Name of class {property1: value; property 2: value; ...}

With this entry, the class can be applied to any tag (Example 8.2).

Example 8.2. Using classes

 <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Классы</title> <style> .gost { color: green; /* Цвет текста */ font-weight: bold; /* Жирное начертание */ } .term { border-bottom: 1px dashed red; /* Подчеркивание под текстом */ } </style> </head> <body> <p>Согласно <span class="gost">ГОСТ 12.1.003-83 ССБТ &quot;Шум. Общие требования безопасности&quot;</span>, шумовой характеристикой рабочих мест при постоянном шуме являются уровни звуковых давлений в децибелах в октавных полосах. Совокупность таких уровней называется <b class="term">предельным спектром</b>, номер которого численно равен уровню звукового давления в октавной полосе со среднегеометрической частотой 1000&nbsp;Гц. </p> </body> </html> 

The result of applying the classes to the <span> and <b> tags is shown in fig. 8.2.

  Classes in CSS

Fig. 8.2. The appearance of tags, designed using classes

Classes are useful when you need to apply a style to different elements of a web page: table cells, links, paragraphs, etc. Example 8.3 shows changing the background color of table lines to create a zebra.

Example 8.3. Using classes

 <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Камни</title> <style> table.jewel { width: 100%; /* Ширина таблицы */ border: 1px solid #666; /* Рамка вокруг таблицы */ } th { background: #009383; /* Цвет фона */ color: #fff; /* Цвет текста */ text-align: left; /* Выравнивание по левому краю */ } tr.odd { background: #ebd3d7; /* Цвет фона */ } </style> </head> <body> <table class="jewel"> <tr> <th>Название</th><th>Цвет</th><th>Твердость по Моосу</th> </tr> <tr class="odd"> <td>Алмаз</td><td>Белый</td><td>10</td> </tr> <tr> <td>Рубин</td><td>Красный</td><td>9</td> </tr> <tr class="odd"> <td>Аметист</td><td>Голубой</td><td>7</td> </tr> <tr> <td>Изумруд</td><td>Зеленый</td><td>8</td> </tr> <tr class="odd"> <td>Сапфир</td><td>Голубой</td><td>9</td> </tr> </table> </body> </html> 

The result of this example is shown in Fig. 8.3. In the example, the class named odd is used to change the background color of the table row. Due to the fact that this class is not added to all tags <tr> and it turns out the alternation of different colors.

  Classes in CSS

Fig. 8.3. Result of applying classes

Simultaneous use of different classes

Multiple classes can be added to any tag at the same time by listing them in the class attribute separated by spaces. In this case, the element is applied the style described in the rules for each class. Since, when adding several classes, they may contain the same style properties, but with different values, the value is taken from the class, which is described in the code below.

Example 8.4 shows the use of different classes to create a tag cloud.

Example 8.4. Combination of different classes

 <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Облако тегов</title> <style type="text/css"> .level1 { font-size: 1em; } .level2 { font-size: 1.2em; } .level3 { font-size: 1.4em; } .level4 { font-size: 1.6em; } .level5 { font-size: 1.8em; } .level6 { font-size: 2em; } A.tag { color: #468be1; /* Цвет ссылок */ } </style> </head> <body> <div> <a href="/term/2" class="tag level6">Paint.NET</a> <a href="/term/69" class="tag level6">Photoshop</a> <a href="/term/3" class="tag level5">цвет</a> <a href="/term/95" class="tag level5">фон</a> <a href="/term/11" class="tag level4">палитра</a> <a href="/term/43" class="tag level3">слои</a> <a href="/term/97" class="tag level2">свет</a> <a href="/term/44" class="tag level2">панели</a> <a href="/term/16" class="tag level1">линия</a> <a href="/term/33" class="tag level1">прямоугольник</a> <a href="/term/14" class="tag level1">пиксел</a> <a href="/term/27" class="tag level1">градиент</a> </div> </body> </html> 

The result of this example is shown in Fig. 8.4.

  Classes in CSS

Fig. 8.4. Tag Cloud

Styles are also allowed to use an entry of the form .layer1.layer2, where layer1 and layer2 are class names. The style is applied only to elements that have the classes layer1 and layer2 set at the same time.

Questions to check

1. What class name is spelled correctly?

  1. 2layer1
  2. 1layer
  3. Yndex
  4. pink-floyd
  5. 28_days_later

2. What color will the word “stream” have in the code ?

<p class = "c1"> The utilization rate emitted by lamps <span class = "c2 c3"> flux </ span>, on the design plane. </ p>

When using the following style?

BODY {color: red; }
P {color: green; }
.c1 {color: blue; }
.c2 {color: yellow; }
.c3 {color: orange; }
.c2.c3 {color: black; }

  1. Green.
  2. Blue.
  3. Yellow.
  4. Orange.
  5. The black.

3. How to set the style of the <div class = "iddqd"> DOOM </ div> tag?

  1. div [iddqd] {color: red; }
  2. div.iddqd {color: red; }
  3. iddqd.div {color: red; }
  4. div # iddqd {color: red; }
  5. div = iddqd {color: red; }

4. What class name should be added to the <P> tag so that the text is both bold and red in color if the following style is available?

s1 {color: red; font-weight: bold; }
.s2 {color: red; }
.s3 {background-color: red; font-weight: bold; }
.s4 {font-weight: bold; }
.s5 {font: red bold; }

  1. s1
  2. s2
  3. s3
  4. s2 s4
  5. s5

Answers

1. pink-floyd

2. Black.

3. div.iddqd {color: red; }

4. s2 s4

created: 2014-10-19
updated: 2021-03-13
132637



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Cascading CSS / CSS3 Style Sheets

Terms: Cascading CSS / CSS3 Style Sheets