You get a bonus - 1 coin for daily activity. Now you have 1 coin

CSS Pseudo Elements

Lecture



Pseudo-elements allow you to set the style of elements of document elements that are not defined in the tree, as well as generate content that is not in the source code of the text.

The syntax for using pseudo-elements is as follows.

Selector: Pseudo-element {Description of style rules}

First comes the name of the selector, then a colon is written, followed by the name of the pseudo-element. Each pseudo-element can be applied only to one selector, if you need to install several pseudo-elements for one selector at once, the style rules should be added to them separately, as shown below.

.foo: first-letter {color: red}
.foo: first-line {font-style: italic}

Pseudo-elements cannot be applied to internal styles, only to a table of related or global styles.

The following are all pseudo-elements, their description and properties.

after

Used to insert assigned content after the content of an item. This pseudo-element works in conjunction with the content style property, which defines the content to insert. Example 16.1 shows the use of the after pseudo-element to add text to the end of a paragraph.

Example 16.1. Application: after

HTML5CSS 2.1IE 7IE 8 + CrOpSaFx

<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Псевдоэлементы</title> <style> P.new:after { content: " - Новьё!"; /* Добавляем после текста абзаца */ } </style> </head> <body> <p class="new">Ловля льва в пустыне с помощью метода золотого сечения.</p> <p>Метод ловли льва простым перебором.</p> </body> </html> 


The result of the example is shown in Fig. 16.1.

  CSS Pseudo Elements

Fig. 16.1. Adding text to a paragraph using: after

In this example, an additional word is added to the contents of a paragraph with the class new, which is the value of the content property.

Pseudo-elements: after and: before, as well as the style property content are not supported by Internet Explorer browser up to version seven inclusive.

: before

By its action: before is similar to the pseudo-element: after, but inserts content before the content of the element. Example 16.2 shows how to add markers of your type to list items by hiding standard markers and applying the: before pseudo-element.

Example 16.2. Usage: before

HTML5CSS 2.1IE 7IE 8 + CrOpSaFx 4

 <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Псевдоэлементы</title> <style> UL { padding-left: 0; /* Убираем отступ слева */ list-style-type: none; /* Прячем маркеры списка */ } LI:before { content: "\20aa "; /* Добавляем перед элементом списка символ в юникоде */ } </style> </head> <body> <ul> <li>Чебурашка</li> <li>Крокодил Гена</li> <li>Шапокляк</li> <li>Крыса Лариса</li> </ul> </body> </html> 


The result of the example is shown below (fig. 16.2).

  CSS Pseudo Elements

Fig. 16.2. Change the appearance of markers with: before

In this example, the pseudo-element: before is set for the LI selector, which defines the elements of the list. Adding the desired characters occurs by setting the value of the content property. Please note that the text is not necessarily the argument, unicode characters may also be used.

And: after and: before give the result only for those elements that have content, therefore adding to the selector img or it will not output anything.

: first-letter

Specifies the style of the first character in the text of the element to which it is added. This allows you to create a letter and a protruded initial in the text.

The initial letter is an enlarged first letter whose baseline is down one or more lines of the base line of the main text. The protruding initial is an enlarged uppercase letter whose baseline coincides with the baseline of the main text.

Consider an example of creating a protruding initial. To do this, add the pseudo-element: first-letter to the P selector and set the desired initial style. In particular, increase the size of the text and change the color of the text (Example 16.3).

Example 16.3. Usage: first-letter

HTML5CSS 2.1IECrOpSaFx

 <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Псевдоэлементы</title> <style> P { font-family: Arial, Helvetica, sans-serif; /* Гарнитура шрифта основного текста */ font-size: 90%; /* Размер шрифта */ color: black; /* Черный цвет текста */ } P:first-letter { font-family: 'Times New Roman', Times, serif; /* Гарнитура шрифта первой буквы */ font-size: 200%; /* Размер шрифта первого символа */ color: red; /* Красный цвет текста */ } </style> </head> <body> <p>Луч фонарика высветил старые скрипучие ступени, по которым не далее как пять минут назад в дом поднялся Паша. Оля осторожно приоткрыла дверь и посветила внутрь дома. Луч света, словно нехотя, пробивался сквозь тугую завесу из мрака и пыли. </p> <p>Взгляд Оли опустился на пол, и она вскрикнула. В пустом помещении никого не было, и лишь на полу валялась порванная туфля Паши.</p> </body> </html> 


The result of the example is shown below (fig. 16.3).

  CSS Pseudo Elements

Fig. 16.3. Create a performing initial

In this example, the font, size, and color of the first letter of each paragraph of text are changed.

: first-line

Specifies the style of the first line of block text. The length of this string depends on many factors, such as the font used, the size of the browser window, the width of the block, the language, etc.

Not all style properties can be applied to the pseudo-element: first-line. It is permissible to use properties related to the font, changing the color of the text and background, as well as: clear, line-height, letter-spacing, text-decoration, text-transform, vertical-align and word-spacing.

Example 16.4 shows the use of the: first-line pseudo-element as applied to a paragraph of text.

Example 16.4. Select the first line of text

HTML5CSS 2.1IECrOpSaFx

 <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Псевдоэлементы</title> <style> P:first-line { color: red; /* Красный цвет текста */ font-style: italic; /* Курсивное начертание */ } </style> </head> <body> <p>Интересно, а существует ли способ действительно практичного применения свойства first-line? Нет, не такого, чтобы можно было бы показать, что это возможно, а чтобы воистину захватило дух от красоты решения, загорелись глаза от скрытых перспектив, после чего остается только сказать себе, что вот это вот, это самое сделать по-другому, также изящно и эффектно просто невозможно.</p> </body> </html> 


The result of the example is shown in Fig. 16.4.

  CSS Pseudo Elements

Fig. 16.4. The result of the pseudo-element: first-line

In this example, the first line is highlighted in red and in italic. Please note that when changing the width of the browser window, the style of the first line remains constant, regardless of the number of words included in it.

Questions to check

1. What pseudo-element allows you to add text to the beginning of a sentence?

  1. after
  2. : before
  3. : first-line
  4. : first-text
  5. : first-letter

2. What does the next style do?

OL LI: first-letter {
color: red;
}

  1. Changes the color of the first letter of a bulleted item.
  2. Changes the color of the first letter of a numbered list item.
  3. Changes the color of the first line in a bulleted list.
  4. Changes the color of the first line in a numbered list.
  5. Changes the text color of the entire list.

3. Which selector is written with an error?

  1. p.new:before
  2. abbr: first-line
  3. p.new.back: after
  4. div: before: first-letter
  5. a: hover: before

Answers

1.: before

2. Changes the color of the first letter of a numbered list item.

3. div: before: first-letter

CSS on topic

  • Pseudo-element: after
  • Pseudo-element: before
  • Pseudo element: first-letter
  • Pseudo-element: first-line

Practical work

  • Quote
  • Cards
  • Carved corners
created: 2014-10-19
updated: 2021-03-13
376



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