search
HomeWeb Front-endFront-end Q&AWhat is the difference between css3 pseudo-classes and pseudo-elements?

Difference: 1. Pseudo-classes are used to add corresponding styles to existing elements when they are in a certain state, while pseudo-elements are used to create some elements that are not in the DOM tree and add styles to them; 2. Pseudo elements will create an element outside the document tree, but pseudo classes will not; 3. Pseudo elements are represented by a double colon "::", and pseudo classes are represented by a single colon ":".

What is the difference between css3 pseudo-classes and pseudo-elements?

The operating environment of this tutorial: Windows 7 system, CSS3&&HTML5 version, Dell G3 computer.

What are pseudo-classes and pseudo-elements

When the word "pseudo" is mentioned, what do you think of? "Fake", "Wang Jingwei's pseudo-government", "non-existent"...

pseudo-class: used when existing elements are in a certain state (sliding, Click, etc.) to add corresponding styles to it. This state changes dynamically based on user behavior. My understanding is that it is a state that does not exist in itself and will only be triggered under specific circumstances (sliding, clicking). You can use CSS to modify the object in this state. For example: when the user hovers over a specified element, you can use :hover to describe the state of the element. Although it is similar to general CSS and can add styles to existing elements, it can only be used in a state that cannot be described by the DOM tree. Elements add styles, so they are called pseudo-classes.

Pseudo elements: Used to create some elements that are not in the DOM tree and add styles to them. For example, we can use :before to add some text before an element and add styles to the text. Although the user can see the text, it is not actually in the DOM document.

The difference between pseudo-classes and pseudo-elements:

Please see the following example:

Example 1:

<ul>
 <li>第一列</li>
 <li>第二列</li>
</ul>

If we want to add a style to the first column, we can do it in the following two ways:

(1) Add a class to the first column and define the style in the class:

<ul>
  <li class="first-item">第一列</li> 
  <li>第二列</li></ul>
</ul>

.first-item{color:orange;}

(2) If there is no need to add a class, we can add styles to the first

  • by setting: first-child pseudo-class. At this time, the modified li still exists in the DOM tree. Medium
    <ul>
      <li>第一个</li>
      <li>第二个</li>
    </ul>
    
    
    li:first-child{color:orage;}

    Example 2:

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

    If you want to add a style to the first letter of the paragraph, you can do the following:

    (1) Wrap the first letter element, and set the style for span:

    <p>
      <span class="first">H</span>ello World, and wish you have a good day!
    </p> 
    
    
    .first{color:red;}

    (2) If the element is not created, we can set the P:first-letter pseudo-element to the

    element. Add a style. At this time, it looks like a virtual span element is created and a style is added to it, but in fact this span element does not exist in the DOM

    <p>Hello World, and wish you have a good day!</p>
    
    p:first-letter{color:red;}

    From the above example we can see: The operating object of the pseudo class is an existing element in the document tree, while the pseudo element creates an element outside the document tree. Therefore, the difference between pseudo-classes and pseudo-elements is whether an element outside the document tree is created.

    Use single or double colons for pseudo elements?

    The css3 specification requires the use of double colons (::) to represent pseudo-elements to distinguish pseudo-classes and pseudo-elements. For example, pseudo-elements such as ::before and ::after use double colons. The colon (::), :hover and :active pseudo-classes use a single colon (:). Except for some browsers lower than IE8, most browsers support the double colon (::) representation method of pseudo elements.

    However, except for a few pseudo-elements such as ::backdrop, which must use double colons (::), most pseudo-elements support single colon and double colon writing, such as ::after, which can be written as:after. run.

    The w3c standard states that although the CSS3 standard requires pseudo elements to be written with double colons, single colon writing is still supported. For backward compatibility, we recommend that you still use the single colon writing method for now.

    Commonly used pseudo-classes are:

    :active selects the element that is being activated (matches the specified state)

    :hover selects the element that is hovered by the mouse Element (matches the specified status)

    :link Selects elements that have not been visited (matches the specified status)

    :visited Selects elements that have been visited (matches the specified status)

    :first-child selects the element that is the first child element of its parent element

    :lang(value) selects the element with the specified lang attribute

    :focus selects the keyboard input focus Elements

    :enable Selects each enabled element

    :disable Selects each disabled element

    :checked Selects each selected element

    :target selects the current anchor element

    :first-of-type selects the element that is the first child element of a certain type of its parent element

    :last-of- type selects the element that is the last child element of a certain type of its parent element

    :only-of-type selects the element that is the only child element of a certain type of its parent element

    : nth-of-type(n) Selects the element that is the nth child element of a certain type of its parent element

    :nth-last-of-type(n) Selects the element that is the penultimate child element of its parent element n elements of a certain type

    :only-child selects the element that is the only child element of its parent element

    :last-child selects the element that is the last element of its parent element

    :nth-child(n) selects the element that is the nth child element of its parent element

    :nth-last-child(n) Selects elements that are the n-th child element from the bottom of its parent element

    :empty Selects elements that have no child elements

    :in-range selection Select elements whose value is within the specified range

    :out-of-range Select elements whose value is not within the specified range

    :invalid Select elements whose value is invalid

    :valid Selects elements that satisfy the valid value

    :not(selector) Selects elements that do not satisfy selector

    :optional Selects form elements that are optional, that is, there is no "required" attribute

    :read-only selects the form element with "readonly"

    :read-write selects the form element without "readonly"

    :root selects the root element

    Commonly used pseudo-elements

    ::first-letter Selects the first word of the specified element

    ::first-line Selects the first line of the specified element

    ::after Insert content before the content of the specified element

    ::before Insert content after the content of the specified element

    ::selection Select the content selected by the user in the specified element

    (Learning video sharing: css video tutorial)

  • The above is the detailed content of What is the difference between css3 pseudo-classes and pseudo-elements?. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Understanding useState(): A Comprehensive Guide to React State ManagementUnderstanding useState(): A Comprehensive Guide to React State ManagementApr 25, 2025 am 12:21 AM

    useState()isaReacthookusedtomanagestateinfunctionalcomponents.1)Itinitializesandupdatesstate,2)shouldbecalledatthetoplevelofcomponents,3)canleadto'stalestate'ifnotusedcorrectly,and4)performancecanbeoptimizedusinguseCallbackandproperstateupdates.

    What are the advantages of using React?What are the advantages of using React?Apr 25, 2025 am 12:16 AM

    Reactispopularduetoitscomponent-basedarchitecture,VirtualDOM,richecosystem,anddeclarativenature.1)Component-basedarchitectureallowsforreusableUIpieces,improvingmodularityandmaintainability.2)TheVirtualDOMenhancesperformancebyefficientlyupdatingtheUI.

    Debugging in React: Identifying and Resolving Common IssuesDebugging in React: Identifying and Resolving Common IssuesApr 25, 2025 am 12:09 AM

    TodebugReactapplicationseffectively,usethesestrategies:1)AddresspropdrillingwithContextAPIorRedux.2)HandleasynchronousoperationswithuseStateanduseEffect,usingAbortControllertopreventraceconditions.3)OptimizeperformancewithuseMemoanduseCallbacktoavoid

    What is useState() in React?What is useState() in React?Apr 25, 2025 am 12:08 AM

    useState()inReactallowsstatemanagementinfunctionalcomponents.1)Itsimplifiesstatemanagement,makingcodemoreconcise.2)UsetheprevCountfunctiontoupdatestatebasedonitspreviousvalue,avoidingstalestateissues.3)UseuseMemooruseCallbackforperformanceoptimizatio

    useState() vs. useReducer(): Choosing the Right Hook for Your State NeedsuseState() vs. useReducer(): Choosing the Right Hook for Your State NeedsApr 24, 2025 pm 05:13 PM

    ChooseuseState()forsimple,independentstatevariables;useuseReducer()forcomplexstatelogicorwhenstatedependsonpreviousstate.1)useState()isidealforsimpleupdatesliketogglingabooleanorupdatingacounter.2)useReducer()isbetterformanagingmultiplesub-valuesorac

    Managing State with useState(): A Practical TutorialManaging State with useState(): A Practical TutorialApr 24, 2025 pm 05:05 PM

    useState is superior to class components and other state management solutions because it simplifies state management, makes the code clearer, more readable, and is consistent with React's declarative nature. 1) useState allows the state variable to be declared directly in the function component, 2) it remembers the state during re-rendering through the hook mechanism, 3) use useState to utilize React optimizations such as memorization to improve performance, 4) But it should be noted that it can only be called on the top level of the component or in custom hooks, avoiding use in loops, conditions or nested functions.

    When to Use useState() and When to Consider Alternative State Management SolutionsWhen to Use useState() and When to Consider Alternative State Management SolutionsApr 24, 2025 pm 04:49 PM

    UseuseState()forlocalcomponentstatemanagement;consideralternativesforglobalstate,complexlogic,orperformanceissues.1)useState()isidealforsimple,localstate.2)UseglobalstatesolutionslikeReduxorContextforsharedstate.3)OptforReduxToolkitorMobXforcomplexst

    React's Reusable Components: Enhancing Code Maintainability and EfficiencyReact's Reusable Components: Enhancing Code Maintainability and EfficiencyApr 24, 2025 pm 04:45 PM

    ReusablecomponentsinReactenhancecodemaintainabilityandefficiencybyallowingdeveloperstousethesamecomponentacrossdifferentpartsofanapplicationorprojects.1)Theyreduceredundancyandsimplifyupdates.2)Theyensureconsistencyinuserexperience.3)Theyrequireoptim

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    MantisBT

    MantisBT

    Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor