search
HomeWeb Front-endCSS TutorialCSS pseudo-selector learning pseudo-element selector analysis

CSS pseudo-selector learning pseudo-element selector analysis

Aug 03, 2022 am 10:45 AM
cssPseudo elementSelectorPseudo class

In the previous article "What is a hierarchical selector in CSS? how to use? ", we learned about 4 types of hierarchical selectors. Let's talk about pseudo-selectors. They provide more complex functions, but do not directly correspond to the elements that HTML documents should have. There are two main types of pseudo-selectors: pseudo-elements and pseudo-classes. Let’s first talk about pseudo-element selectors in detail.

CSS pseudo-selector learning pseudo-element selector analysis

Pseudo-element selector

Pseudo-element selector in CSS is to add keywords to the specified CSS selector. Used to describe the styling of a specific part of a specified element. [Recommended learning: css video tutorial]

Through pseudo-elements, developers can define styles for specific parts of the selected element without using the ID or class attributes of the element. For example, through pseudo-elements you can set the style of the first letter in a paragraph, or insert some content before or after the element, etc.

In CSS1 and CSS2, the use of pseudo-elements is the same as pseudo-classes, and a colon : is connected to the selector. However, in CSS3, the use of single colon for pseudo elements was changed to double colon :: to distinguish pseudo classes and pseudo elements. Therefore, it is recommended to use double colons instead of single colons when using pseudo-elements.

The syntax structure is as follows:

/* CSS3 语法 */
选择器::伪元素 {
  属性 : 属性值;
}
/* CSS2 过时语法 (仅用来支持 IE8) */
选择器:伪元素 {
  属性 : 属性值;
}

should now use two colons, unless you are also compatible with IE8.

Note: Only one pseudo-element can be used in a selector, and the pseudo-element must follow the selector. According to the latest W3C specification, you should use double colon :: instead of single colon : when defining pseudo-elements to distinguish pseudo-classes and pseudo-elements. However, since the old version of the W3C specification did not make a special distinction, most browsers currently support both single colon and double colon methods to define pseudo-elements.

CSS provides a series of pseudo-elements, as shown in the following table:

##:: selectionp::selectionMatch the part of the element selected by the user::placeholderinput::placeholderMatch the placeholder attribute of each form input box (such as )

::before和::after伪元素

::before 伪元素 的作用是作为定位的HTML元素的第一个子级元素,::after ** 伪元素** 的作用是作为定位的 HTML元素的最后一个子级元素。

如下示例代码展示了::before::after伪元素的用法:

nbsp;html>



    <meta>
    <meta>
    <meta>
    <title>::before和::after伪元素</title>
    <style>
        p::before {
            content: "♥";
        }

        p::after {
            content: "♥";
        }
    </style>



    <p>这是一段测试内容</p>


代码运行结果如下图所示:

CSS pseudo-selector learning pseudo-element selector analysis

如上述示例代码所示,::before伪元素和::after伪元素通常会配合content属性来为该元素增加装饰内容。

content属性用于在元素的::before伪元素和::after伪元素中插入内容。该属性具有的值如下所示:

  • none:不会产生伪类元素。

  • normal::before伪元素和::after伪类元素中会被视为 none。

  • text:文本内容。

  • url:格式为url(),指定一个外部资源(比如图片)。如果该资源或图片不能显示,它就会被忽略或显示一些占位。

::first-letter和::first-line伪元素

::first-letter::first-line伪元素分别匹配文本的第一个字和第一行的样式内容。示例代码如下:

nbsp;html>



    <meta>
    <meta>
    <meta>
    <title>::first-letter和::first-line伪元素</title>
    <style>
        /* 匹配第一行 */
        p::first-line {
            background-color: lightcoral;
        }

        /* 匹配第一个字 */
        p::first-letter {
            font-size: 130%;
        }
    </style>



    <p>我如果爱你——绝不像攀援的凌霄花,借你的高枝炫耀自己;</p>


代码运行结果如下图所示:

CSS pseudo-selector learning pseudo-element selector analysis

值得注意的是::first-letter::first-line伪元素可以使用的CSS属性是有限制的。

::first-letter选择器可以设置的CSS属性:

  • font属性

  • color属性

  • background属性

  • margin属性

  • padding属性

  • border属性

  • text-decoration属性

  • vertical-align属性

  • text-transform属性

  • line-height属性

  • float属性

  • clear属性

::first-line选择器可以设置的CSS属性:

  • font属性

  • color属性

  • background属性

  • word-spacing属性

  • letter-spacing属性

  • text-decoration属性

  • vertical-align属性

  • text-transform属性

  • line-height属性

  • clear属性

::selection伪元素

::selection伪元素的作用是匹配用户在HTML页面选中的文本内容(比如使用鼠标或其他选择设备选中的部分)设置高亮效果。如下示例代码展示了::selection伪元素的用法:

nbsp;html>



    <meta>
    <meta>
    <meta>
    <title>::first-letter和::first-line伪元素</title>
    <style>
        p::selection {
            color: gold;
            background-color: red;
        }
    </style>



    <p>我如果爱你——绝不像攀援的凌霄花,借你的高枝炫耀自己;</p>


代码运行结果如下图所示:

CSS pseudo-selector learning pseudo-element selector analysis

::placeholder伪元素

伪元素 ::placeholder 用来设置表单元素(

<!DOCTYPE html>
<html>
<head>
    <style>
        input.text::placeholder{
            color: red;
            background-color: #CCC;
        }
    </style>
</head>
<body>
    <input placeholder="请输入一段文本">未使用伪元素 ::placeholder<br>
    <input placeholder="请输入一段文本" class="text">使用伪元素 ::placeholder 的效果
</body>
</html>

代码运行结果如下图所示:

CSS pseudo-selector learning pseudo-element selector analysis

(学习视频分享:web前端入门

Pseudo-elements Example Example description
::after p::after Insert content after each

element

::before p::before Insert content before each

element

::first-letter p::first-letter Matches the first letter of the content in each

element

::first-line p::first-line Matches the first line of content in each

element

The above is the detailed content of CSS pseudo-selector learning pseudo-element selector analysis. 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
Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)May 09, 2025 am 09:57 AM

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

CSS Animations: Is it hard to create them?CSS Animations: Is it hard to create them?May 09, 2025 am 12:03 AM

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

@keyframes CSS: The most used tricks@keyframes CSS: The most used tricksMay 08, 2025 am 12:13 AM

@keyframesispopularduetoitsversatilityandpowerincreatingsmoothCSSanimations.Keytricksinclude:1)Definingsmoothtransitionsbetweenstates,2)Animatingmultiplepropertiessimultaneously,3)Usingvendorprefixesforbrowsercompatibility,4)CombiningwithJavaScriptfo

CSS Counters: A Comprehensive Guide to Automatic NumberingCSS Counters: A Comprehensive Guide to Automatic NumberingMay 07, 2025 pm 03:45 PM

CSSCountersareusedtomanageautomaticnumberinginwebdesigns.1)Theycanbeusedfortablesofcontents,listitems,andcustomnumbering.2)Advancedusesincludenestednumberingsystems.3)Challengesincludebrowsercompatibilityandperformanceissues.4)Creativeusesinvolvecust

Modern Scroll Shadows Using Scroll-Driven AnimationsModern Scroll Shadows Using Scroll-Driven AnimationsMay 07, 2025 am 10:34 AM

Using scroll shadows, especially for mobile devices, is a subtle bit of UX that Chris has covered before. Geoff covered a newer approach that uses the animation-timeline property. Here’s yet another way.

Revisiting Image MapsRevisiting Image MapsMay 07, 2025 am 09:40 AM

Let’s run through a quick refresher. Image maps date all the way back to HTML 3.2, where, first, server-side maps and then client-side maps defined clickable regions over an image using map and area elements.

State of Devs: A Survey for Every DeveloperState of Devs: A Survey for Every DeveloperMay 07, 2025 am 09:30 AM

The State of Devs survey is now open to participation, and unlike previous surveys it covers everything except code: career, workplace, but also health, hobbies, and more. 

What is CSS Grid?What is CSS Grid?Apr 30, 2025 pm 03:21 PM

CSS Grid is a powerful tool for creating complex, responsive web layouts. It simplifies design, improves accessibility, and offers more control than older methods.

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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools