search
HomeWeb Front-endCSS TutorialDetailed introduction and usage summary of CSS3 selectors

CSS3NewA lot of powerful selectors

It allows us to write less jsEventsScript
Let’s first take a look at the selectors of each version.
Note:
ele represents element element
attr represents attributeattribute, val represents value attribute value
:xxx They all belong to pseudo class selectors, and ::xxx all belong to pseudoelement selectors
I have subdivided the named selectors as much as possible

CCS1 selector

##ele,eleParallel selectorh1,h2Select all h1 elements and h2 elementsele elep pSelect all p elements within the p elementa:linkSelect unvisited linksPseudo class selectora:visitedSelect visited linksPseudo class selectora:activeSelect active linkPseudo-class selectora:hoverSelect mouse hover link:First letter selectorp:first-letterSelect the first letter of each p element:First line selectorp:first-lineSelect the first line of each p element

The CSS1 version has our most commonly used classic selectors
::first-letter and ::first-line seem to be rarely used
In CSS2, they can only be used in paragraphs and the like Block-level elements, hyperlinks and other inline elements cannot be used
In CSS2.1, :first-letter can be applied to all elements
but there are still restrictions on the attributes they can use
I won’t list it here. After all, it’s not commonly used


Link pseudo-class selector (anchor pseudo-class). We usually use

a:link {color: blue;}             /*静态伪类:未访问链接时蓝色*/a:visited {color: purple;}        /*静态伪类:访问过的链接变为紫色*/a:hover {color: red;}             /*动态伪类:鼠标悬浮在链接上变为红色*/a:active {color: orange;}         /*动态伪类:鼠标按下链接时变为橘黄色*/

link-visited-hover-active (LVHA) is the recommended order and will not cause conflicts due to overwriting
It is also easy to remember "greening LVHuA"

CSS2 selector

Selector Type Example Description
.class Class selector .demo Select all elements whose class contains demo
#id ID selector #unique Select all elements whose id is unique
ele Element selector p Select all p elements
Descendant selector
:link Pseudo-classSelector
: visited
:active
:hover
:first-letter
:first-line
##*Wildcard selector *Select all elementsele>eleDirectp>pSelect the p element whose parent is the p elementele+eleAdjacent sibling element selectorp+pSelect a p element immediately after the p element[attr][target]Selects elements with target attribute[attr=val] Attribute selector[target=_blank]Select elements with target attribute and attribute value _blank[attr~=val] Attribute selector[title~=demo]Select elements that have the title attribute and contain the word "demo"[attr|=Attribute selector[lang|=en]Select the starting value of the lang attribute as EN ElementFocus selectorinput:focusSelect the element that has focus input elementFirst child selectorp:first-childSelect the element whose p element is the first child of its parent:Pseudo-element selectorp::beforeInsert content before the p element:Pseudo element selection Devicep::afterInsert content after the p elementPseudo-class selectorp:lang(it)Select the p element whose starting value of the lang attribute is it

这里需要注意的有p+p相邻兄弟元素选择器
选择的是紧挨着p元素后的一个p元素,
发现一些网站和书上写的都是所有p元素,但我验证了一下发现好像不对

title~demo是说title属性包含demo这个词,属性值之间用空格分隔的单词
像这样<img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/194/a585037cdb77e4c20a8bf750ba362bb3-0.png?x-oss-process=image/resize,p_40" class="lazy" title="demo demo1 demo2" alt="Detailed introduction and usage summary of CSS3 selectors" >是可以选中的
但是<img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/194/a585037cdb77e4c20a8bf750ba362bb3-0.png?x-oss-process=image/resize,p_40" class="lazy" title="demo1 demo2" alt="Detailed introduction and usage summary of CSS3 selectors" >就不能够选中

语言的选择器不常用过就不说了

::before和::after伪元素选择器要想添加内容,需要使用content属性

p::before {    content: "123";}

我们用after的时候很多时候是为了清除浮动

p::after {    content: "";    display: block;    clear: both;}

至于为什么就不是今天讨论的范畴了( ̄_, ̄ )

伪类与伪元素

伪元素选择器写成伪类单冒号的形式没什么问题
但是伪类选择器使用双冒号就不能选择元素了

这里说一下伪类伪元素的区别
伪类我的理解是元素达到一种状态
状态存在,改变样式;状态消失,样式消失
伪元素应该说是操作元素的特定内容
实在分不清都写成单冒号的形式就好了

CSS3选择器

敲这么多终于到关键地方了
CSS3增加了很多强大的选择器,以伪劣选择器为主
CSS1和CSS2版本的选择器加起来都没它多
我们一起来看一下

selector Type Example Description
Child element selector
Attribute Selector
language]
:focus
:first-child
:before
:after
:lang(language)
Selector Category Example Description
ele~ele After sibling element selector p~p Select all p elements after the p element
[attr^=val] Attribute selector a[src^=https] Select elements whose src attribute value starts with https
[attr$=val] Attribute selector a[src$=\.pdf] Select the src attribute value to .pdf Ending element
[attr*=val] Attribute selector a[src*=demo] select The value of the src attribute contains the sub stringdemo element
:first-of-type pseudo-class selection p:first-of-type Selects the first p element for each p element that is its parent
:last-of-type Pseudo-class selector p:last-of-type Selects each p element that is the last of its parent p element
:only-of-type pseudo-class selector p:only-of-type select Each p element is the only p element of its parent
:only-child Unique child element selector p:only-child Select each p element that is the only child element of its parent
:nth-child(n) Pseudo-class selector p:nth-child(2) Select each p element that is the second child element of its parent
:nth-last-child (n) Pseudo-class selector p:nth-last-child(2) Selects each p element as the penultimate child of its parent Element
:nth-of-type(n) Pseudo-class selector p:nth-of-type(2) Select the second p element for which each p element is its parent
:nth-last-of-type(n) pseudo-class Selector p:nth-last-of-type(2) Selects each p element is the penultimate p element of its parent
:last-child Pseudo-class selector p:last-child Selects each p element that is the last child element of its parent
:root Root element selector :root Select the document root element
:empty emptyTag selector p:empty Select p elements without any child elements (including text nodes)
:target Target element selector new:target Select the currently active # new element (contains the URL clicked by the anchor name)
:enabled Pseudo-class selector input:enabled select Enabled input elements
:disabled Pseudo-class selector input:disabled Select disabled input elements
:checked Pseudo class selector input:checked Select the selected input element
:not(selector) Negative selector :not(p) Select elements that are not p elements
::selection Highlight text selector ::selection The matching element is selected by the user or is in a highlighted state Part of
:out-of-range pseudo-class selector :out-of-range Select input elements whose values ​​are outside the specified range
:in-range Pseudo-class selector :in-range Select input elements whose values ​​are within the specified range
:read-write Read-write element selector :read-write Select elements that are readable and writable
:read-only Read-only element selector :read-only Select read-only elements with the readonly attribute set
:optional Pseudo-class selector :optional Select optional input elements
:required Pseudo-class selector :required Select elements with the required attribute set
:valid Legal element selector :valid Select elements with legal input values
:invalid Illegal element selector :invalid Select elements with illegal input values

属性选择器

[attr^=val],[attr$=val],[attr*=val] 这三个属性选择器放在一起记
也很好记,很想我们正则表达式中用的开头匹配符^,结尾匹配符$,统配匹配符*
同时还要区别于CSS2中的[attr~=val]

<p class="demo demo1">1</p><p class="demo demo2">2</p><p class="demo demo3">3</p>

[class^=de]可以把三行都选中,因为它们的class属性都是以“de”开头的
[class$=o2]可以选中第二行,因为只有它的class属性是以“o2”结尾的
[class*=em]同样可以选中三行,因为它们class的都包含字符串“em”
[class~=de]不能选中任何行,因为它class中以空格分隔的属性值中没有“de”的属性值

说到这个属性选择器,我还要多说一点
我在表格中的示例是这么写的 a[src$=\.pdf]
是因为“.”它不认识,我们需要加“\”转义
不过css中属性选择器也可以写成引号的形式
比如说下面代码时等价的
a[src$=\.pdf]
a[src$=".pdf"]
a[src$='.pdf']

子元素选择器

下面的一堆什么type、child的选择器都是针对子元素在父元素中的位置的
表格中列出的很详细了
我主要谈谈type、child的区别,
以最简单的:first-child和:first-of-type为例

<p>0</p><p>1</p><p>2</p><p>3</p>
p:first-child{    background-color: red;}


使用first-child我们发现页面没有变化
这是因为p并不是body元素的第一个子元素


p:first-of-type{/*改*/
    background-color: red;}


改为first-of-type我们发现第一个p变红了
这是因为它是body元素的子元素中所有p的第一个

其他的也是一样的道理,举一反三

根元素选择器

:root这个选择器没什么意思,和你直接使用html一样

:root {...}
html {...}

空元素选择器

:empty就是选择真正的空元素,内部没有任何子元素,文本节点也不能有
举个例子

<p></p><p>1</p><p>2</p><p>3</p>
p:empty::before {    content: "12345";    background-color: gold;}

目标元素选择器

这个:target选择器还有点意思
写一个例子

<a href="#first">1st</a><br><a href="#second">2nd</a><br><a href="#third">3rd</a><br><a href="#fourth">4th</a><br><a href="#fifth">5th</a><br><br><br><br><br><br><p id="first">1</p><p id="second">2</p><p id="third">3</p><p id="fourth">4</p><p id="fifth">5</p>
body {    height: 2000px;}p {    width: 200px;    height: 200px;    font: 200px/200px bold;}

这是一个小demo可以利用锚点在页面中进行跳转
点击链接可以跳转到对应id的元素,并且url链接也发生了改变

此时就会触发:target的样式
我们来试一试,加几行代码

p:target {    background-color: deeppink;}

再点击链接

我们发现,跳转的同时,p样式改变了

高亮文本选择器

::selection是CSS3新增的选择器
它用来匹配突出显示的文本(用鼠标选择文本)
浏览器有默认的样式(背景为蓝色,字体为)

<p>this is a long long text...</p>
p::selection{    color: white;    background-color: dodgerblue;}

浏览器默认的样式就是相当于这样,我们可以自己修改

否定选择器

:not()这个选择器可以排除某些特定条件的元素
比如说我们可以这样用

<p class="demo">1</p><p>2</p><p>3</p>
p:not(.demo) {    background-color: aqua;}


这样类属性中有demo的元素就不会变色

CSS小图表

剩下的选择器大部分都是针对input输入标签的
不详细讲了
我们做一个小练习,仅仅用CSS3的选择器做一个点击按钮切换图片的小图表
通过点击单选框显示不同的图片
像这样

首先我们需要编写html代码
使用三个radio和三个img元素

<input type="radio" name="demo" id="a" checked><img  src="/static/imghwm/default1.png"  data-src="a.jpg"  class="lazy"    alt="Detailed introduction and usage summary of CSS3 selectors" ><input type="radio" name="demo" id="b"><img  src="/static/imghwm/default1.png"  data-src="b.jpg"  class="lazy"   alt="Detailed introduction and usage summary of CSS3 selectors" ><input type="radio" name="demo" id="c"><img  src="/static/imghwm/default1.png"  data-src="c.jpg"  class="lazy"   alt="Detailed introduction and usage summary of CSS3 selectors" >

然后css部分通过:checked配合条件选择器控制img元素的显示

input {    margin-left: 35px;}img {    display: none;}:checked+img {    position: absolute;    left: 10px;    top: 40px;    display: inline-block;}

这样我们就完成了我们的小图表功能


整理了一晚上的选择器,可能会有遗漏的
如果想起来,日后再补吧

The above is the detailed content of Detailed introduction and usage summary of CSS3 selectors. 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
@keyframes vs CSS Transitions: What is the difference?@keyframes vs CSS Transitions: What is the difference?May 14, 2025 am 12:01 AM

@keyframesandCSSTransitionsdifferincomplexity:@keyframesallowsfordetailedanimationsequences,whileCSSTransitionshandlesimplestatechanges.UseCSSTransitionsforhovereffectslikebuttoncolorchanges,and@keyframesforintricateanimationslikerotatingspinners.

Using Pages CMS for Static Site Content ManagementUsing Pages CMS for Static Site Content ManagementMay 13, 2025 am 09:24 AM

I know, I know: there are a ton of content management system options available, and while I've tested several, none have really been the one, y'know? Weird pricing models, difficult customization, some even end up becoming a whole &

The Ultimate Guide to Linking CSS Files in HTMLThe Ultimate Guide to Linking CSS Files in HTMLMay 13, 2025 am 12:02 AM

Linking CSS files to HTML can be achieved by using elements in part of HTML. 1) Use tags to link local CSS files. 2) Multiple CSS files can be implemented by adding multiple tags. 3) External CSS files use absolute URL links, such as. 4) Ensure the correct use of file paths and CSS file loading order, and optimize performance can use CSS preprocessor to merge files.

CSS Flexbox vs Grid: a comprehensive reviewCSS Flexbox vs Grid: a comprehensive reviewMay 12, 2025 am 12:01 AM

Choosing Flexbox or Grid depends on the layout requirements: 1) Flexbox is suitable for one-dimensional layouts, such as navigation bar; 2) Grid is suitable for two-dimensional layouts, such as magazine layouts. The two can be used in the project to improve the layout effect.

How to Include CSS Files: Methods and Best PracticesHow to Include CSS Files: Methods and Best PracticesMay 11, 2025 am 12:02 AM

The best way to include CSS files is to use tags to introduce external CSS files in the HTML part. 1. Use tags to introduce external CSS files, such as. 2. For small adjustments, inline CSS can be used, but should be used with caution. 3. Large projects can use CSS preprocessors such as Sass or Less to import other CSS files through @import. 4. For performance, CSS files should be merged and CDN should be used, and compressed using tools such as CSSNano.

Flexbox vs Grid: should I learn them both?Flexbox vs Grid: should I learn them both?May 10, 2025 am 12:01 AM

Yes,youshouldlearnbothFlexboxandGrid.1)Flexboxisidealforone-dimensional,flexiblelayoutslikenavigationmenus.2)Gridexcelsintwo-dimensional,complexdesignssuchasmagazinelayouts.3)Combiningbothenhanceslayoutflexibilityandresponsiveness,allowingforstructur

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

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 Article

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software