Reprinted from AlloyTeam:www.alloyteam.com/2016/05/sum…

Anyone familiar with the front end has heard of CSS pseudo-classes and pseudo-elements, yet most people confuse the two. This article starts from parsing the meaning of pseudo-classes and pseudo-elements, and distinguishes the difference between the two, and lists most of the specific use of pseudo-classes and pseudo-elements, even if you have used pseudo-classes and pseudo-elements, but there must be one or two you have not seen.

1. Pseudo-classes and pseudo-elements

Here’s why CSS introduced pseudo-elements and pseudo-classes: CSS introduced the concept of pseudo-classes and pseudo-elements to format information outside of the document tree. That is, pseudo-classes and pseudo-elements are used to modify parts that are not in the document tree, such as the first letter in a sentence or the first element in a list. Pseudo-classes and pseudo-elements are explained as follows:

Pseudo-classes are used to style existing elements when they are in a state that changes dynamically based on user behavior. For example, when a user hovers over a specified element, we can use :hover to describe the state of the element. Although it is similar to a normal CSS class in that it can style existing elements, it can only style elements in a state that the DOM tree cannot describe, so it is called a pseudo-class.

Pseudo-elements are used to create and style elements that are not in the document tree. For example, we can append some text to an element and style the text with :before. Although this text is visible to the user, it is not actually in the document tree.

2. The difference between pseudo-classes and pseudo-elements

Here are two examples to illustrate the difference.

Example 1:

<ul>
    <li>I was the first</li>
    <li>I was the second</li>
</ul>
Copy the code

If you want to add a style to the first item, you can add a class for the first

  • and define the style in that class:
  • HTML:

    <ul>
        <li class="first-item">I was the first</li>
        <li>I was the second</li>
    </ul>
    Copy the code

    CSS:

    li.first-item {
        color: orange
    }
    Copy the code

    Instead of adding class methods, we can style the first

  • : first-Child pseudo-class. At this point, the modified
  • element is still in the document tree.
  • HTML:

    <ul>
        <li>I was the first</li>
        <li>I was the second</li>
    </ul>
    Copy the code

    CSS:

    li:first-child {
        color: orange
    }
    Copy the code

    Example 2:

    <p>Hello World, and wish you have a good day!</p>
    Copy the code

    If you want to style the first letter of the paragraph, wrap a < SPAN > element around the first letter and style the SPAN element:

    HTML:

    <p><span class="first">H</span>ello World, and wish you have a good day!</p>
    Copy the code

    CSS:

    .first {
        font-size: 5em;
    }
    Copy the code

    Instead of creating a element, we can style it by setting the ::first-letter pseudo-element of

    . At this point, it looks as if a virtual element has been created and styled, but the element does not actually exist in the document tree.

    HTML:

    <p>Hello World, and wish you have a good day!</p>
    Copy the code

    CSS:

    p:first-letter {
        font-size: 5em;
    }
    Copy the code

    As you can see from the example above, the pseudo class operates on an existing element in the document tree, while the pseudo element creates an element outside the document tree. Thus, the difference between a pseudo class and a pseudo element is whether an element outside the document tree is created

    3. Do pseudo-elements use single or double colons?

    In my opinion, according to the requirements of CSS3 specification, double colons (::) are used to denote pseudo-elements and single colons (:) are used to denote pseudo-classes, so as to distinguish pseudo-elements from pseudo-classes. With the exception of some browsers later than IE8, most browsers support the double colon (::) notation for pseudo-elements.

    4. Specific usage of pseudo-classes and pseudo-elements

    This chapter lists the specific uses of most pseudo-classes and pseudo-elements in terms of meaning parsing and examples. Here are the summary diagrams of pseudo-classes by usage and pseudo-elements by colon:

    pseudo-classes

    Pseudo elements

    Some pseudo classes or pseudo elements are still in the experimental stage and it is recommended to check browser compatibility on sites like Can I Use before using them. Experimental pseudo classes or pseudo elements are labeled in the title.

    Pseudo elements

    1 ::before/:before

    :before Inserts content before the selected element. You need to use the Content property to specify what to insert. The inserted content is not actually in the document tree.

    HTML:

    <h1>World</h1>
    Copy the code

    CSS:

    h1:before {
        content: "Hello ";
    }
    Copy the code

    2 ::after/:after

    :after inserts content after the element. Its usage and properties are similar to :before.

    3 ::first-letter/:first-letter

    :first-letter Matches the first letter of the Chinese text element. The decorated initial is not in the document tree.

    CSS:

    h1:first-letter  {
        font-size: 5em;
    }
    Copy the code

    4 ::first-line/:first-line

    :first-line Matches the text of the first line in the element. This pseudo-element can only be used in block elements, not inline elements.

    CSS:

    p:first-line {
        background: orange;
    }
    Copy the code

    5 ::selection

    :: Selection Matches the part of the user that is selected or highlighted by the user. The -moz prefix is required when using Firefox. This pseudo-element only supports the double colon form.

    CSS:

    ::-moz-selection {
        color: orange;
        background: # 333;
    }
     
    ::selection  {
        color: orange;
        background: # 333;
    }
    Copy the code

    6 ::placeholder

    ::placeholder matches the text of the placeholder, which is valid only if the element has a placeholder attribute. This pseudo-element is not a CSS standard, and its implementation may change in the future, so use it with caution. In some browsers (IE10 and Firefox18 and below) the single colon form is used.

    HTML:

    <input type="email" placeholder="[email protected]">
    Copy the code

    CSS:

    input::-moz-placeholder {
        color:# 666;
    }
     
    input::-webkit-input-placeholder {
        color:# 666;
    }
     
    /* IE 10 only */
    input:-ms-input-placeholder {
        color:# 666;
    }
     
    /* Firefox 18 and below */
    input:-moz-input-placeholder {
        color:# 666;
    }
    Copy the code

    The water is in the trial phase.

    The :: Backdrop backdrop is used to change the background color in the full-screen mode. The default color is black. This pseudo-element only supports the double colon form

    HTML:

    <h1 id="element">This heading will have a solid background color in full-screen mode.</h1>
    <button onclick="var el = document.getElementById('element'); el.webkitRequestFullscreen();">Trigger full screen!</button>
    Copy the code

    CSS:

    h1:fullscreen::backdrop {
        background: orange;
    }
    Copy the code

    pseudo-classes

    state

    Since the use of state pseudo-classes is well known, we will not use examples here.

    • :link – Selects unaccessed links
    • :visited – Selects links that have been visited
    • :hover – Selects the element over which the mouse pointer floats
    • :active – Selects active links
    • :focus – Selects the input field to get focus

    structured

    1 :not

    A negation pseudo-class that matches elements that do not match the argument selector.

    In the following example, the text of all

  • elements except the first
  • element turns orange.
  • HTML:

    <ul>
        <li class="first-item">Some text</li>
        <li>Some text</li>
        <li>Some text</li>
        <li>Some text</li>
    </ul>
    Copy the code

    CSS:

    li:not(.first-item) {
        color: orange;
    }
    Copy the code

    2 :first-child

    Matches the first child of the element.

    In the following example, the text of the first

  • element turns orange.
  • HTML:

    <ul>
        <li>The text here is orange</li>
        <li>Some text</li>
        <li>Some text</li>
    </ul>
    Copy the code

    CSS:

    li:first-child {
        color: orange;
    }
    Copy the code

    3 : last-child

    Matches the last child of the element.

    In the following example, the text of the last

  • element turns orange.
  • HTML:

    <ul>
        <li>Some text</li>
        <li>Some text</li>
        <li>The text here is orange</li>
    </ul>
    Copy the code

    CSS:

    li:last-child {
        color: orange;
    }
    Copy the code

    4 first-of-type

    Matches each element of the first child element of a specific type that belongs to its parent.

    In the following example, the text of the first

  • element and the first element turns orange.
  • HTML:

    <ul>
        <li>The text here is orange</li>
        <li>Some text<span>The text here is orange</span></li>
        <li>Some text</li>
    </ul>
    Copy the code

    CSS:

    ul :first-of-type {
        color: orange;
    }
    Copy the code

    5 :last-of-type

    Matches the last child of the element.

    In the following example, the text of the last

  • element turns orange.
  • HTML:

    <ul>
        <li>Some text<span>Some text</span> <span>The text here is orange</span></li>
        <li>Some text</li>
        <li>The text here is orange</li>
    </ul>
    Copy the code

    CSS:

    ul :last-of-type {
        color: orange;
    }
    Copy the code

    6 :nth-child

    :nth-child matches one or more elements based on their position. It takes an argument of the form an+b. An +b matches an element as shown in the following example:

    • 1n plus 0, or n, matches each child element.
    • 2n+0, or 2n, matching positions 2, 4, 6, 8… This expression is equivalent to the keyword even.
    • 2n+1 Matches positions 1, 3, 5, 7… The expression is equivalent to the keyword odd.
    • 3n+4 matches positions 4, 7, 10, 13… Child element of.

    As an example, there is the following HTML list:

    <ol>
        <li>Alpha</li>
        <li>Beta</li>
        <li>Gamma</li>
        <li>Delta</li>
        <li>Epsilon</li>
        <li>Zeta</li>
        <li>Eta</li>
        <li>Theta</li>
        <li>Iota</li>
        <li>Kappa</li>
    </ol>
    Copy the code

    CSS:

    Select the second element and the “Beta” will turn orange:

    ol :nth-child(2) {
        color: orange;
    }
    Copy the code

    “Beta”, “Delta”, “Zeta”, and “kappa” turn orange when selecting elements whose positions are multiples of 2:

    ol :nth-child(2n) {
        color: orange;
    }
    Copy the code

    Select the element with an even number:

    ol :nth-child(even) {
        color: orange;
    }
    Copy the code

    Select elements with positions as multiples of 2, starting at number 6, and “Zeta”, “Theta”, and “Kappa” will turn orange:

    ol :nth-child(2n+6) {
        color: orange;
    }
    Copy the code

    7 :nth-last-child

    : nth-last-Child is similar to :nth-child except that it starts counting from the last child.

    8 :nth-of-type

    :nth-of-type is similar to nth-child except that it matches only elements of a specific type.

    In the following example, the second

    element turns orange.

    HTML:

    <article>
        <h1>I am heading</h1>
        <p>Some text</p>
        <a href=""><img src="images/rwd.png" alt="Mastering RWD"></a>
        <p>The text here is orange</p>
    </article>
    Copy the code

    CSS:

    p:nth-of-type(2) {
        color: orange;
    }
    Copy the code

    9 :nth-last-type

    :nth-last-of-type is similar to nth-of-type except that it starts counting from the last child element.

    10 :only-child

    When an element is the only child of its parent, :only-child matches the element.

    HTML:

    <ul>
        <li>The text here is orange</li>
    </ul>
     
    <ul>
        <li>Some text</li>
        <li>Some text</li>
    </ul>
    Copy the code

    CSS:

    ul :only-child {
        color: orange;
    }
    Copy the code

    11 :only-of-type

    When an element is the only child of a particular type within its parent, :only-child matches that element.

    In the following example, the first UL element has only one element of type Li, and the text of the li element turns orange.

    HTML:

    <ul>
        <li>The text here is orange</li>
        <p>This is not orange</p>
    </ul>
     
    <ul>
        <li>Some text</li>
        <li>Some text</li>
    </ul>
    Copy the code

    CSS:

    li:only-of-type {
        color: orange;
    }
    Copy the code

    12 :target

    When the URL has an anchor name that points to a specific element in the document, :target matches that element.

    In the following example, the target in the URL hits the article element whose ID is target, and the background of the article element turns yellow.

    URL:

    example.com/#target

    HTML:

    <article id="target">
        <h1><code>:target</code> pseudo-class</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit!</p>
    </article>
    Copy the code

    CSS:

    :target {
        background: yellow;
    }
    Copy the code

    The form related

    1 :checked

    : Checked matches the checked input element, which includes radio and checkbox.

    In the following example, when the checkbox is selected, the background of the

    HTML:

    <input type="checkbox"/>
    <label>I agree with</label>
    Copy the code

    CSS:

    input:checked + label {
        background: yellow;
    }
    Copy the code

    2 :default

    :default Matches elements selected by default. For example, the submit button is always the default button on the form.

    In the example below, only the background of the submit button turns yellow.

    HTML:

    <form action="#">
        <button>reset</button>
        <button type="submit">submit</button>
    </form>
    Copy the code

    CSS:

    :default  {
        background: yellow;
    }
    Copy the code

    3 :disabled

    :disabled Matches the disabled form elements.

    For example, the opacity of the disabled input box becomes 50%.

    HTML:

    <input type="text" disabled/>
    Copy the code

    CSS:

    :disabled {
        opacity:.5;
    }
    Copy the code

    4 :empty

    :empty matches elements that have no children. If the element contains a text node, HTML element, or a space, then :empty will not match the element.

    As an example, elements that match :empty turn yellow.

    • The first element has text nodes, so its background doesn’t turn yellow;
    • The second element has a space. If there is a space, the element is not empty, so its background does not turn yellow.
    • The third element has nothing in it, so the background is yellow;
    • The fourth element has only one comment, which is empty, so its background turns yellow;

    HTML:

    <div>The background in this container is orange</div>
    <div> </div>
    <div></div>
    <div><! -- This comment is not considered content --></div>
    Copy the code

    CSS:

    div {
        background: orange;
        height: 30px;
        width: 200px;
    }
     
    div:empty {
        background: yellow;
    }
    Copy the code

    5 :enabled

    :enabled Matches form elements that do not have the disabled attribute set.

    6 :in-range

    :in-range Matches elements in the specified range.

    For example, when the number selector is between 5 and 10, the border of the number selector is set to green.

    HTML:

    <input type="number" min="5" max="10">
    Copy the code

    CSS:

    input[type=number] {
        border: 5px solid orange;
    }
     
    input[type=number]:in-range {
        border: 5px solid green;
    }
    Copy the code

    7 :out-of-range

    :out-of-range, as opposed to :in-range, matches elements that are not in the specified range.

    8 :indeterminate

    Indeterminate means indeterminate. When checkboxes or checkboxes ina group are not selected: IndeTerminate Matches all checkboxes or checkboxes in the group.

    For example, if none of the boxes below is checked, the background of the label element next to the input is set to orange.

    HTML:

    <ul>
        <li>
            <input type="radio" name="list" id="option1">
            <label for="option1">Option 1</label>
        </li>
        <li>
            <input type="radio" name="list" id="option2">
            <label for="option2">Option 2</label>
        </li>
        <li>
            <input type="radio" name="list" id="option3">
            <label for="option3">Option 3</label>
        </li>
    </ul>
    Copy the code

    CSS:

    :indeterminate + label {
        background: orange;
    }
    Copy the code

    9 :valid

    :valid Match condition verifies the correct form element.

    For example, when the value in the email input box matches the email format, the border of the input box is set to green.

    HTML:

    <input type="email"/>
    Copy the code

    CSS:

    input[type=email]:valid {
        border: 1px solid green;
    }
    Copy the code

    10 :invalid

    :invalid In contrast to :valid, the matching condition validates the wrong form element.

    11 :optional

    A :optional match is a form element with the optional attribute. When the form element is not set to Required, it is the Optional attribute.

    For example, the background of the first input will not be set to yellow and the background of the second input will be set to yellow.

    HTML:

    <input type="text" required />
    <input type="text" />
    Copy the code

    CSS:

    :optional {
        background: yellow;
    }
    Copy the code

    12 :required

    : Required matches the form element with the Required attribute set, as opposed to :optional.

    13 :read-only

    :read-only Matches elements with a read-only attribute. Form elements can be defined as read-only by setting the readonly attribute.

    In the following example, the background of the input element is set to yellow.

    HTML:

    <input type="text" value="I am read only" readonly>
    Copy the code

    CSS:

    input:read-only {
        background-color: yellow;
    }
    Copy the code

    14 :read-write

    :read-write Matches the elements in the edit state. Input, Textarea, and HTML elements with contenteditable Settings are edited when they get focus.

    In the following example, when input fields and rich text fields get focus, the background turns yellow.

    HTML:

    <input type="text" value="Background turns yellow while gaining focus"/>
     
    <div class="editable" contenteditable>
        <h1>Click here to edit it</h1>
        <p>The background turns yellow while getting focus</p>
    </div>
    Copy the code

    CSS:

    :read-write:focus {
        background: yellow;
    }
    Copy the code

    15: Scope (in experimental stage)

    :scope matches elements in the style scope. When a style has no scope attribute set, the style within the style applies to the entire HTML.

    In the following example, the text of the element in the second section becomes italic.

    HTML:

    <article>
        <section>
            <h1>Very normal some text</h1>
            <p>Very normal some text</p>
        </section>
        <section>
            <style scoped>
                :scope {
                    font-style: italic;
                }
            </style>
            <h1>The text here is in italics</h1>
            <p>The text here is in italics</p>
        </section>
    </article>
    Copy the code

    Note: The only browser that currently supports this pseudo-class is Firefox.

    Language related

    1: DIR (experimental)

    :dir matches the element specified for reading direction. This pseudo-class takes effect only when the DIR attribute is set in an HTML element. There are currently two reading directions supported: LTR (left to right) and RTL (right to left). Currently, only Firefox supports the dir pseudo-class, which is prefixed when used in Firefox (-moz-dir()).

    For example, Arabic text in the P element (Arabic is read from right to left) turns orange.

    HTML:

    <article dir="rtl">
    <p>An ل ت د ل ي ك organisation an ح د م ن أ ق د م an ل ع ل organisation م an ل ص ح ي ة an ل ت ي ع ر ف ه an an ل an ن س an ن organisation an ل ذ ي ي ت م an س ت خ د an م ه ل أ غ an ض an ل ش ف an ء م ن ذ organisation ل an ه an ل ط ف ل.</p>
    </article>
    Copy the code

    CSS:

    /* prefixed */
    article :-moz-dir(rtl) {
        color: orange;
    }
     
    /* unprefixed */
    article :dir(rtl) {
        color: orange;
    }
    Copy the code

    For example, the English text in the P element turns blue

    HTML:

    <article dir="ltr">
        <p>Free If you already know some HTML and CSS and understand the principles of responsive Web Design, then this book is for you.</p>
    </article>
    Copy the code

    CSS:

    article :-moz-dir(ltr) {
        color: blue;
    }
     
    /* unprefixed */
    article :dir(ltr) {
        color: blue;
    }
    Copy the code

    2 :lang

    :lang matches language-specific elements. You can set the language by setting the lang= “” attribute for HTML elements, the charset=” “attribute for meta elements, or the language attribute on the HTTP header.

    In fact, the lang= “” attribute can be set not only on HTML tags, but also on other elements.

    Here is an example of setting different reference styles for different languages:

    HTML:

    <article lang="en">
        <q>Lorem ipsum dolor sit amet.</q>
    </article>
    <article lang="fr">
        <q>Lorem ipsum dolor sit amet.</q>
    </article>
    <article lang="de">
        <q>Lorem ipsum dolor sit amet.</q>
    </article>
    Copy the code

    CSS:

    :lang(en) q { quotes: ' ' ' ' ' '; }
    :lang(fr) q { quotes: ' ' ' ' ' '; }
    :lang(de) q { quotes: ' ' ' ' ' '; }
    Copy the code

    other

    1 :root

    :root Matches the root element of the document. The root element of a normal HTML file is an HTML element, while the root element of an SVG or XML file may be something else.

    For example, set the background of an HTML element to orange

    :root {
        background: orange;
    }
    Copy the code

    2.:fullscreen

    :fullscreen Matches elements in full-screen mode. Fullscreen mode is not a full-screen mode that is opened by pressing F11. Instead, it is opened through Javascript’s Fullscreen API, which varies from browser to browser. Currently, :fullscreen requires a prefix to be used.

    For example, when in full screen mode, the background of the H1 element turns orange

    HTML:

    <h1 id="element">In full screen mode, the background of the text here will turn orange.</h1>
    <button>Enter full screen mode!</button>
    Copy the code

    JAVASCRIPT:

    var docelem = document.getElementById('element');
    var button = document.querySelector('button');
    button.onclick = function() {
        if (docelem.requestFullscreen) {
            docelem.requestFullscreen();
        }else if (docelem.webkitRequestFullscreen) {
            docelem.webkitRequestFullscreen();
        } else if(docelem.mozRequestFullScreen) {
            docelem.mozRequestFullScreen();
        } else if(docelem.msRequestFullscreen) { docelem.msRequestFullscreen(); }}Copy the code

    CSS:

    h1:fullscreen {
        background: orange;
    }
     
    h1:-webkit-full-screen {
        background: orange;
    }
     
    h1:-moz-full-screen {
        background: orange;
    }
     
    h1:-ms-fullscreen {
        background: orange;
    }
    Copy the code