CSS | Псевдоэлементы

Опубликовано: 1 Марта, 2022

Псевдоэлементы: Псевдоэлемент в CSS используется для добавления стиля в определенные части элемента. Пример: использование стиля до или после элемента.

Syntax:

selector::pseudo-element {
    property:value;
}

Use of Pseudo-Element: Below are some examples to describe the use of pseudo-element.

  • ::before Pseudo-element: It is used to add some CSS property before an element when that element is called.
    Example:
    <html>
    <head>
        <title>before</title>
        <style>
        h1::before {
            content: "Before element - ";
        }
        </style>
    </head>
    <body>
        <h1>GFG</h1>
        <p>It is a paragraph.</p>
        <p>This is another paragraph.</p>
    </body>
    </html>

    Output:

  • ::after Pseudo-element: It is used to add some CSS property after an element when that element is called.
    Example:
    <html>
    <head>
        <title>after</title>
        <style>
        h1::after {
            content: " - after element";
        }
        </style>
    </head>
    <body>
        <h1>GFG</h1>
        <p>It is a paragraph.</p>
        <p>This is another paragraph.</p>
    </body>
    </html>

    Output:

  • ::first-letter Pseudo-element: It is used to make changes to the first letter of an element.
    Example:
    <html>
    <head>
        <title>after</title>
        <style>
        h1::first-letter {
            color: #ff0000;
        }
        </style>
    </head>
    <body>
        <h1>GFG</h1>
        <p>It is a paragraph.</p>
        <p>This is another paragraph.</p>
    </body>
    </html>

    Output:

  • ::first-line Pseudo-element: It is used to make changes to the first line of an element.
    Example:
    <html>
    <head>
        <title>after</title>
        <style>
        h1::first-line {
            color: #ff0000;
        }
        </style>
    </head>
    <body>
        <h1>GFG</h1>
        <p>It is a paragraph.</p>
        <p>This is another paragraph.</p>
    </body>
    </html>

    Output: