define

Why pseudo-classes, pseudo-elements

CSS introduced the concept of pseudo-classes and pseudo-elements to format information beyond 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

What is a pseudo-class

Pseudo-classes are used to style existing elements when they are in a state that changes dynamically based on user behavior. 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

A pseudo-class is a colon (:) followed by the name of the pseudo-class, sometimes followed by a value in parentheses (:nth-child).

What is a pseudo-element

A pseudo-element is a virtual element that CSS treats as a normal HTML element. They are called pseudo-elements because they do not actually exist in the document tree or DOM. In other words, we don’t include pseudo-elements in HTML, only CSS to create them

The pseudo-element is one colon or two colons

Short answer: most of the time, yes.

The CSS3 specification requires the use of double colons (::) to distinguish pseudo-elements from pseudo-classes. With the exception of IE8 and below, all browsers support the pseudo-element notation of two colons.

Some pseudo-elements can only use two colons, like ::backdrop

Single-colon notation is recommended because of backward compatibility. The CSS3 standard requires that pseudo-elements be written with double colons, but single-colon notation is still supported

When to use (and not use) generated content

Generating content with CSS uses the CSS property Content and pseudo-elements :before or :after

The content can be plain text, or it can be a container that uses CSS operations to display a graphic or decorative element.

Don’t use generated content for important content for the following reasons:

  1. Screen readers can’t read it
  2. Unable to select the
  3. If superfluous content is used in the generated content for decoration purposes, screen readers that support CSS generated content will read it aloud, resulting in a worse user experience

pseudo-classes

State pseudo-classes

Usually occurs when a user performs an operation; Link, visited, hover, active, focus

Order: LVHA cannot be messed up

a:link { color: blue } /* Not accessed link */
a:visited { color: purple } /* Already accessed link */
a:hover { font-weight: bold } /* User mouse hover */
a:active { color: lime } /* Activate links */
Copy the code

:FOCUS

:focus is used to select elements that are already focused by a pointer device, touch, or keyboard, and is used a lot in forms

a:focus {
    color: green;
}
input:focus {
    background: #eee;
}
Copy the code

Structured pseudo-class

Structured pseudo-classes select other information in the document tree or DOM that cannot be selected by other selectors

:first-child Selects the first child of the parent element

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

:last-child Selects the last child of the parent element

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

:first-of-type Selects the first element of any type of child element in the parent element container

The text for the first Li element and the first SPAN element is red

:last-of-type Selects the last element of any type of child element in the parent element container

The text for the last Li element and the last SPAN element is orange

<ul>
    <li>Lorem ipsum dolor sit amet. <span>Lorem ipsum dolor sit amet.</span> <span>This text will be orange.</span></li>
    <li>Lorem ipsum dolor sit amet.</li>
    <li>This text will be orange.</li>
</ul>
Copy the code
ul :first-of-type {
    color: red;
}

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

:nth-child selects the corresponding element based on its order in the tag

First find all siblings of the current element, then sort by position starting from 1. The selection results in CSS pseudo-classes: the set of elements (n= 0,1,2,3…) matched by the expression (an+b) in parentheses nth-child.

: NTH pseudo-classes all take one argument, which is a formula. The formula can be an integer, or the keyword odd, even, or a structure of the form an+b.

  • A is a number (integer)
  • N is n
  • + is the operator, which can be plus + or minus –
  • B is also an integer, but only if the operator is used
<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

Select the second child and Beta will turn orange:

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

Starting with the second child, the Beta, Delta, Zeta, Theta, and Kappa turn orange

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

Select all even-numbered children

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

Zeta, Theta, and Kappa turn orange by selecting the other element from the sixth child:

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

:nth-of-type:nth-childsimilar

The main difference is that it is more specific, targeting only certain types of elements

The second p element in all containers will be orange

<article>
    <h1>Heading Goes Here</h1>
    <p>Lorem ipsum dolor sit amet.</p>
    <a href=""></a>
    <p>This text will be orange.</p>
</article>
Copy the code
p:nth-of-type(2) {
    color: orange;
}
Copy the code

:nth-last-child Selects elements from back to front

Use exactly the same as :nth-child

:NTH-LAST-OF-TYPE

Count from back to front. The rest is the same as :nth-of-type

:only-child Selects the only child of the parent element

The first UL has only one child element, so that child element will be orange. The second UL has multiple child elements, so the child elements are not affected by the :only- Child pseudo-class

<ul>
    <li>This text will be orange.</li>
</ul>

<ul>
    <li>Lorem ipsum dolor sit amet.</li>
    <li>Lorem ipsum dolor sit amet.</li>
</ul>
Copy the code
ul :only-child {
    color: orange;
}
Copy the code

:only-of-type Selects the element of the unique type at the same level

Similar to :only-child, but for certain types of elements, the selector has a stronger meaning.

The first UL has only one li element, so its text will be orange:

<ul>
    <li>This text will be orange.</li>
</ul>

<ul>
    <li>Lorem ipsum dolor sit amet.</li>
    <li>Lorem ipsum dolor sit amet.</li>
</ul>
Copy the code
li:only-of-type {
    color: orange;
}
Copy the code

:target Selects elements by their ID and anchor name in the URL

When the URL in the browser ends with #target, the article with the ID target is selected

http://awesomebook.com/#target
Copy the code
<article id="target">
    <h1><code>:target</code> pseudo-class</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit!</p>
</article>
Copy the code
:target {
    background: yellow;
}
Copy the code

The :not pseudo-class is also called the antipseudo-class, which selects elements that do not match the arguments

It takes one argument, a “selector,” through parentheses. In fact, this argument could also be another pseudo-class.

This pseudo-class can be used by concatenation, but cannot contain anything else: the not selector

<ul>
    <li class="first-item">Lorem ipsum dolor sit amet.</li>
    <li>Lorem ipsum dolor sit amet.</li>
    <li>Lorem ipsum dolor sit amet.</li>
    <li>Lorem ipsum dolor sit amet.</li>
</ul>
Copy the code

The text of the li element, except for.first-item li, is orange:

li:not(.first-item) {
    color: orange;
}
Copy the code
“Concatenate” two :not pseudo class

Apply the following CSS rules to all li’s except those with a. First-item class and the last li, with a yellow background and black text:

li:not(.first-item):not(:last-of-type) {
    background: yellow;
    color: black;
}
Copy the code

Verify the pseudo class

Although the pseudo classes described in this section are used for form elements, some of them can also be used for other HTML elements.

: Checked Indicates checked radio buttons, multiple option buttons, and list options

When the check box is selected, the background of the

<input type="checkbox"/>
<label>I agree with</label>
Copy the code
input:checked + label {
    background: yellow;
}
Copy the code

:default Selects the default element from a set of similar elements in the form

For example, the submit button is always the default button on the form

<form action="#">
    <button>reset</button>
    <button type="submit">submit</button>
</form>
Copy the code
:default  {
    background: yellow;
}
Copy the code

:disabled Indicates that form elements in the disabled state are selected

The name input box is disabled and therefore translucent:

<input type="text" id="name" disabled>
Copy the code
:disabled {
    opacity:.5;
}
Copy the code

:enabled Selects the enabled element

All form elements are enabled by default, unless the disabled attribute is added to the tag

:enabled {
    opacity: 1;
    border: 1px solid green;
}
Copy the code

:empty Selects an empty element that contains no content

Nothing that contains a letter, other HTML elements, or even a space is empty.

  • The first element contains text, so the background does not turn orange
  • The second element contains a space, which is also content and therefore does not have an orange background
  • There is nothing in the third element (empty), so the background is orange
  • The last element has only one HTML comment (also empty), so it also has an orange background.
<div>This box is orange</div>
<div> </div>
<div></div>
<div><! -- This comment is not considered content --></div>
Copy the code
div {
  background: orange;
  height: 30px;
  width: 200px;
}

div:empty {
  background: yellow;
}
Copy the code

:in-range Selects elements with values within the specified range

In the following example, the input element supports input 5 to 10. Input values within this range trigger a green border

<input type="number" min="5" max="10">
Copy the code
input[type=number] {
    border: 5px solid orange;
}

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

:out-of-range Selects elements with a range and values outside the specified range

In the following example, the input element supports inputs 1 to 12. Input values outside this range trigger an orange border

<input id="months" name="months" type="number" min="1" max="12">
Copy the code
input[type=number]:out-of-range {
    border: 1px solid orange;
}
Copy the code

: Indeterminate Selects radio buttons or check boxes that are not checked when the page loads

For example, after a page loads, there is no default or pre-selected set of radio buttons, or a check box has been set to indeterminate by JavaScript.

<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
:indeterminate + label {
    background: orange;
}
Copy the code

: a valid choiceThe input format meets requirementsForm elements of

If the email format in the email input box is correct, it will take effect and a 1-pixel green border will appear:

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

:invalid Selects inputThe format is invalidForm elements of

An orange border will appear when the email box in the email input field is incorrectly formatted:

input[type=email]:invalid {
    background: orange;
}
Copy the code

:optional Optional input field in the form

As long as the input field does not have a required attribute, it is selected by the: Optional pseudo-class

In the following example, the value field is optional, so the text will be grayed out:

<input type="number">
Copy the code
:optional {
    color: gray;
}
Copy the code

:read-only The pseudo-class selects elements that cannot be edited by the user

Similar to the: Disabled pseudo-class, the attributes used in the tag determine which pseudo-class to use.

The text box has a readonly property and will therefore be checked by :read-only pseudo-classes and the text will be grayed out:

<input type="text" value="I am read only" readonly>
Copy the code
input:read-only {
    color: gray;
}
Copy the code

:read-write The pseudo-class selects elements that the user can edit

Applies to HTML elements that have contenteditable attributes.

Sometimes, it can be used with the: Focus pseudo class to enhance the user experience

To edit the contents of the div element, you can apply special styles to let the user know that you can edit the contents:

<div class="editable" contenteditable>
    <h1>Click on this text to edit it</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit!</p>
</div>
Copy the code
:read-write:focus {
    padding: 5px;
    border: 1px dotted black;
}
Copy the code

The: Required pseudo-class selects the form element with the Required attribute

In addition to being prompted by an asterisk (*) in the tag to be required, you can also apply styles to the input field through this pseudo-class

The input box has the required attribute. Apply a special style to it using this pseudo-class:

<input type="email" required>
Copy the code
:required {
    color: black;
    font-weight: bold;
}
Copy the code

The scope pseudo-class applies when the style tag has a scoped attribute

If a section of the page does not have the scoped attribute in the style tag, the: Scope pseudo-class will look up to the HTML element, which is the default scope of the current stylesheet

In the following example, the second section has a scoped stylesheet, so the text in this section is italicized:

article>
    <section>
        <h1>Lorem ipsum dolor sit amet</h1>
        <p>Lorem ipsum dolor sit amet.</p>
    </section>
    <section>支那<style scoped>
                        :scope {
                            font-style: italic;
                        }
                  </style>支那<h1>This text will be italicized</h1>
        <p>This text will be italicized.</p>
    </section>
</article>
Copy the code

Language class

Language pseudo-classes are related to the text contained in the page, not to media such as images and videos

Including: :dir and :lang

Other pseudo-classes

:root Selects the highest-level parent element in the document

In HTML, the :root pseudo-class selects HTML elements. But in markup languages such as SVG or XML, it might select different elements.

The following rule adds a background color to the highest-level parent HTML element in an HTML document:

:root {
    background: orange;
}
Copy the code

:fullscreen Selects elements to display in full-screen mode (proposal stage)

This does not apply to the Fullscreen mode entered by the user by pressing F11. It only applies to the Fullscreen mode entered by switching through the JavaScript Fullscreen API, which is usually called by images, videos, or games in the parent container

Pseudo elements

::BEFORE/:BEFORE

:before pseudo-elements are similar to :after in that they can add content (text or graphics) to other HTML elements. Again, the content here doesn’t actually exist in the DOM, but you can manipulate it as if it did. You need to declare the Content property in the CSS.

Content generated by this pseudo-element cannot be selected by other selection runes

Whitespace in the content attribute also counts

<h1>Ricardo</h1>
Copy the code
h1:before {
    content: "Hello "; /* Notice the space */ after Hello
}
Copy the code
// The space after the effect "Hello" also counts
Hello Ricardo! 
Copy the code

::AFTER/:AFTER

Anything added by this pseudo-element cannot be selected by any other selection runes

<h1>Ricardo</h1>
Copy the code
h1:after {
    content: ", Web Designer!";
}
Copy the code
/ / the effect
Ricardo, Web Designer!
Copy the code

::BACKDROP BACKDROP

The :: Backdrop backdrop is a box that is generated behind a full-screen element. It can be used with the :fullscreen backdrop class to change the background color of the full-screen element.

::backdrop Double colons must be used for false elements.

:: first-letter /: first-letter selects the FIRST character of a line of text

If the corresponding line is preceded by a picture, video, or table element, the selection of the first character is not affected

This pseudo-element is perfect for typesetting paragraphs without using images or other tricks

This pseudo-element can also be selected :before the first character generated by the pseudo-element

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

:first-line Selects the first line of an element. This applies only to block-level elements, not inline elements

The first line is selected even if the text is multiple lines long

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

:: Selection The highlighted portion of the selection document

Gecko-based browsers require use of the preceding :: :-moz-selection

It is not possible to use both prefixed and unprefixed :: Selection in a single rule

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

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

::placeholder pseudo-elements Select placeholder text set by placeholder properties in form elements (proposal stage)

You can also write it as ::input-placeholder

Reference: www.jianshu.com/p/9086114e0…