【CSS基础】 CSS3选择器

180 阅读3分钟

CSS3选择器有哪些类型呢

111.png

基本选择器

选择器例子描述
**选择所有元素。
elementdiv选择所有 <div> 元素。
#id#container1选择 id="container1" 的元素。
.class.container选择 class="container" 的所有元素。
element, elementdiv,p选择所有 <div> 元素和所有 <p> 元素。
.class1.class2.container1.container2选择 class 属性中同时有 container1 和 container2 的所有元素。

层次选择器

选择器例子描述
.class1 .class2.container1 .container2选择作为类名 container1 元素后代的所有类名 container2 元素。
element>elementdiv>p选择父元素是 <div> 的所有 <p> 元素。
element+elementdiv+p选择紧跟 <div> 元素的首个 <p> 元素。
element~elementdiv~p选择前面有 <p> 元素的每个 <ul> 元素。

属性选择器

选择器例子描述
[target][target]选择带有 target 属性的所有元素。
[target=value][target=_blank]选择带有 target属性为"_blank" 属性的所有元素。
[target*=value]a[href*="abc"]选择其 href 属性值中包含 "abc" 子串的每个 <a> 元素。
[target^=value]a[href^="https"]选择其 href 属性值以 "https" 开头的每个 <a> 元素。
[target$=value]a[href$=".png"]选择其 href 属性值以 "png" 结尾的每个 <a> 元素。

伪类选择器

选择器例子描述
:linka:link选择所有未访问过的链接。
:visiteda:visited选择所有已访问的链接。
:hovera:hover鼠标放到a标签上的时候。
:focusinput:focus选择获得焦点的 input 元素。
:activea:active鼠标点击a标签,但是不松手时。

结构伪类选择器

选择器例子描述
:root:root选择文档的根元素。
:first-childp:first-child选择属于父元素的第一个子元素的每个 <p> 元素。
:last-childp:last-child选择属于父元素的最后一个子元素的每个 <p> 元素。
:nth-child(n)p:nth-child(2)选择属于其父元素的第二个子元素的每个 <p> 元素。
:nth-last-child(n)p:nth-last-child(2)同上,从最后一个子元素开始计数。
:nth-of-type(n)p:nth-of-type(2)选择属于其父元素第二个 <p> 元素的每个 <p> 元素。
:nth-last-of-type(n)p:nth-last-of-type(2)同上,从最后一个子元素开始计数。
:only-childp:only-child选择属于其父元素的唯一子元素的每个 <p> 元素。
:only-of-typep:only-child选择属于其父元素唯一的

元素的每个

元素。

:emptyp:empty选择没有子元素的每个

元素(包括文本节点)。

  • nth-child和nth-of-type区别

:nth-child()表示父元素下的第n个子元素。比如div p:nth-child(2)表示div下的第二的元素、如果不是p元素则 没有匹配的元素  :nth-of-type()表示父元素下的第n个类型的元素 比如div p:nth-of-type(2)表示div下的第二个p元素。

  • nth-child(n)

前3个::nth-child(-n + 3) 后4个::nth-last-child(-n + 4)

UI状态伪类选择器

选择器例子描述
:checkedinput:checked选择每个被选中的 <input> 元素。
:enabledinput:enabled选择每个启用的 <input> 元素。
:disenabledinput:disenabled选择每个被禁用的 <input> 元素。

否定伪类选择器

选择器例子描述
:not:not(p)选择非 <p> 元素的每个元素。

伪元素选择器

选择器例子描述
::first-letterp:first-letter选择每个 <p> 元素的首字母。
::first-linep:first-line选择每个 <p> 元素的首行。
::beforep::before在每个 <p> 的内容之前插入内容。
::afterp::after在每个 <p> 的内容之后插入内容。