概念 - CSS 选择器类型及权重

258 阅读7分钟

Universal Selector(US)

Selects all elements. Optionally, it may be restricted to a specific namespace or to all namespaces. 

Syntax:  * ns|* *|* 

Example:  * will match all the elements of the document.

*{margin:0;padding:0;}

Type Selector(TS 0001)

Type Selector(TS) 又称为元素选择器/标签选择器/类型选择器,即以 html 标签作为 css 修饰所用的选择器。

<!DOCTYPE html>
<html>
    <head>
        <title>元素选择器</title>
        <style>
            p{color:purple;}
        </style>
    </head>
    <body>
        <div>
            <p>雨霖铃</p>
        </div>
    </body>
</html>

Class Selector(CS 0010)

Class Selector(CS),又称为类选择器/Class选择器,可用于描述一组元素的样式。类名和id属性的第一个字符不能使用数字!它无法在 Mozilla 或 Firefox 中起作用。

<!DOCTYPE html>
<html>
    <head>
        <title>class选择器</title>
        <style>
            .text{
                color: cornflowerblue;
            }
            b.text{
                color:purple;
            }
        </style>
    </head>
    <body>
        <b class="text">cornflowerblue n.矢车菊蓝; 矢车菊的蓝色;</b>
        <p class="text">frame_inner_right</p>
    </body>
</html>

ID Selector(IS 0100)

ID Selector(IS) 又称id选择器,可以为标有特定 id 的 HTML 元素指定特定的样式。HTML 元素以 id 属性来设置id选择器,CSS 中 id选择器# 来定义,语法格式#S{...}

<!DOCTYPE html>
<html>
    <head>
        <style>
            #txt{color: blue;}
        </style>
    </head>
    <body>
        <p id="txt">aqua [ˈækwə]n.湖绿色;水(尤用于外包装说明,表示食物、饮料、药物等的水含量); </p>
    </body>
</html>

Attribute Selector(AS)

Selects all elements that have the given attribute.  Syntax: [attr] [attr=value] [attr~=value] [attr|=value] [attr^=value] [attr$=value] [attr*=value]
Example:  [autoplay] will match all elements that have the autoplay attribute set (to any value).

Attribute Selectot 又称属性选择器,是根据元素的属性及属性值来选择元素

ExampleCodeExplanation
属性为age的所有元素标红*[age]{color:red;} [age]{color:red;}匹配写有这个属性,但不一定有属性值
将写有href的a标红a[href]{color:red;}匹配写有这个属性的指定标签
标红写有href和title的a元素a[href][title]{color:red;}匹配写有两个属性,但不一定有属性值的元素
标红name属性为initial的元素[name="initial"]{color:red;}匹配写有对应属性及属性值的节点
描述太阳系行星的XML文档,标红地球CSS:[name="earth"]{color:red;}
XML:<planet name="earth">earth</planet>
匹配xml文档中对应的属性及属性值的节点

属性选择器可以通过类型比较符,匹配元素的某个具体属性。

  1. [attribute~=value] 属性中包含独立的单词为 value
<head>
    <style>
        [name~="initial"]{color: red;}
    </style>
</head>
<body>
    <b name="initial">标红name为initial的元素</b>
</body>
  1. [attribute*=value] 属性中做字符串拆分,只要能拆出来 value 这个词就行
<head>
    <style>
        [name*="flower"]{color: red;}
    </style>
</head>
<body>
    <b name="ffflowerrr1">ffflowerrr1</b>
    <b name="ffflowerrr2">ffflowerrr2</b>
</body>
  1. [attribute|=value] 属性中必须是完整且唯一的单词,或者以 - 分隔开
<!DOCTYPE html>
<html lang="ja"> <!-- lang="ja en" 将不会生效 -->
    <head>
        <style>
            html[lang|="ja"]{color: red;}
        </style>
    </head>
    <body>
        将只设置有日语的html网页的文字为红色
    </body>
</html>
  1. [attribute^=value] 属性的前几个字母是 value 就可以
<!DOCTYPE html>
<html>	
    <head>
        <style>
            [name^="min"]{color: red;}
        </style>
    </head>
    <body>
        <p name="minflower">minflower</p>	
        <p name="malflower">malflower</p>	
        <p name="mineflower">minelower</p>	
        <p name="sexflower">sexlower</p>	
    </body>
</html>
  • 5. [attribute$=value] 属性的后几个字母是 value 就可以
<!DOCTYPE html>
<html>	
	<head>
		<style>
			a[href$=".pdf"]{
				color: red;
			}
		</style>
	</head>
	<body>
		<a href="./huidf890823.pdf">跳转文件</a>
		<a href="./huidf890824.pdf">跳转文件</a>
		<a href="./huidf890825.pdf">跳转文件</a>
	</body>
</html>

Grouping Selector(GS) - Selector list

The , selector is a grouping method that selects all the matching nodes.

Syntax: A, B

Example: div, span will match both <span> and <div> elements.

Grouping Selector(GS) 又称群组选择器/分组选择器/选择器列表(Selector List)

div, span{color:green}

Combinator(组合器 权值求和)

Descendant Combinator(DC)

The " "(space) combinator selects nodes that are descendants of the first element. 

Syntax:  A B 

Example:  div span will match all <span> elements that are inside a <div> element.

Descendant Combinator 又称 Package Selector(PS) 又称包含选择器/后代选择器/后代组合器,当我的元素存在父级元素的时候,要改变自身的样式,可以不另加选择符,直接用包含选择器的方式解决。

语法格式一 A B{...} A、B 为 HTML 元素,表示对与处于A中的B标签有效。

语法格式二 .A B{...} 作用方式同格式一。

语法格式三 .A .B{...} 作用方式同格式一。

语法格式四 A .B{...} 作用方式同格式一。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" name="description" content="HTML,css"/>
        <title>包含选择器Package Selector</title>
        <style>
            div h1{color:red;}
            .container p{font-family: "黑体"}
            .container .main_text {font-family:"fangsong";}
            .container b{color: blueviolet;}
        </style>
    </head>
    <body>
        <div class="container">
            <h1 class="title_one">
                文本标题……
            </h1>
            <p class="first_p">
                首行本文正文……
            </p>
            <span class="main_text">文本正文一</span>
            <br />
            <b>文本正文二</b>
        </div>
    </body>
</html>

Descendant Combinator.png

Child Combinator(CC)

The > combinator selects nodes that are direct children of the first element. 

Syntax:  A > B 

Example:  ul > li will match all <li> elements that are nested directly inside a <ul> element.

Child Combinator 又称子选择器/直接子代组合器

语法格式一 A>B{...} A、B为 HTML 元素。

语法格式二 .A>B{...} 作用同格式一。

语法格式三 .A>.B{...} 作用同格式一。

语法格式四 A>.B{...} 作用同格式一。

    <head>
        <style>
            .container>span{color: blue;}
        </style>
    </head>
    <body>
        <div class="container">
            <span>事不关己的内容</span>
            <div class="header">
                <span>one</span>
                <span>two</span>
            </div>
        </div>
    </body>

General Sibling Combinator(GSC)

The ~ combinator selects siblings. This means that the second element follows the first (though not necessarily immediately), and both share the same parent. 

Syntax:  A ~ B 

Example:  p ~ span will match all <span> elements that follow a <p>, immediately or not.

General Sibling Combinator 又称兄弟选择器/一般兄弟组合器,后一个节点在前一个节点后面的任意位置,并且共享同一个父节点

语法格式一 A~B{...} A、B为HTML元素,表示A标签匹配selector的A,B标签匹配selector的B时,样式显示在B标签,用于同级标签,父子标签无效,并且会决定后面所有相同的同级的标签样式

语法格式二 A~.B{...} 作用同格式一

语法格式三 .A~B{...} 作用同格式一

语法格式四 .A~.B{...} 作用同格式一

<!DOCTYPE html>
<html>
    <head>
        <title>General Sibling Combinator</title>
        <style>
                div~p{color:red;}
                p~div{color: blue;}
        </style>
    </head>
    <body>
        <div>
            <p>演示文本一</p>
            <div>演示文本二</div>
            <b>演示文本三</b>
            <p>演示文本四</p>
            <div>演示文本五</div>
        </div>
    </body>
</html>

General Sibling Combinator.png

Adjacent Sibling Combinator(ASC)

The + combinator matches the second element only if it immediately follows the first element. 

Syntax:  A + B 

Example:  h2 + p will match the first <p> element that immediately follow an <h2> element.

Adjacent Sibling Combinator 又称相邻选择器/紧邻兄弟组合器,匹配紧邻元素的样式,即后一个元素紧跟在前一个之后,并且共享同一个父节点

语法格式一 A+B{...} 样式现在在B元素上。

语法格式二 A+.B{...} 作用同格式一。

语法格式三 .A+B{...} 作用同格式一。

语法格式四 .A+.B{...} 作用同格式一。

<!DOCTYPE html>
<html>
    <head>
        <title>相邻选择器</title>
        <style>
                .container+.third{color: blue;}
                .container+.fourth{color: blueviolet;}/*不相邻,导致效果无效*/
                .first+.second{color: chartreuse;}
                .second+.first{color: burlywood;}/*位置颠倒了,导致效果无效*/
        </style>
    </head>
    <body>
        <div class="container">
            <p class="first">演示文本一</p>
            <p class="second">演示文本二</p>
        </div>
        <p class="third">演示文本三</p>
        <p class="fourth">演示文本四</p>
    </body>
</html>

Pseudo(伪选择器)

Pseudo Classes(PC)

The : pseudo allow the selection of elements based on state information that is not contained in the document tree. 

Example:  a:visited will match all <a> elements that have been visited by the user.

Pseudo Classes 又称为伪类选择器,支持按照未被包含在文档树中的状态信息来选择元素,相当于显示出元素的特殊状态,一般 a 标签用的最多

/* 以下顺序最好不要更改,否则可能导致超链接的样式失效 */
/* 访问之前 */
a:link{
    color: black;
}
/* 访问之后 */
a:visited{ 
    color:red;
}
/* 鼠标在上 */
a:hover{
    color: blue;
}
/* 点击激活 */
a:active{
    color: purple;
}

/* 通过伪类选择后代节点 */
div:hover span{
    display:none;
}
选择器例子
:activea:active
:checkedinput:checked 匹配form表单中处于选中状态的元素
:disabledinput:disabled 匹配form表单中处于不可用状态的元素
:emptyp:empty 匹配标签内部没有任何内容的P元素
:enabledinput:enabled 匹配form表单中处于可用状态的元素
:first-childp:first-child 匹配作为子元素的第一个p标签(即P标签本身需要是某个元素的子元素)
:first-of-typep:first-of-type
:focusinput:focus
:hovera:hover
:in-rangeinput:in-range
:invalidinput:invalid
:lang(language)p:lang(it)
:last-childp:last-child 匹配作为子元素的最后一个p标签(即P标签本身需要是某个元素的子元素)
:last-of-typep:last-of-type
:linka:link
:not(selector):not(p)
:nth-child(n)p:nth-child(2) 匹配p标签的第2个子元素
:nth-last-child(n)p:nth-last-child(2) 匹配作为子元素的底数第二个 p 标签(从最后一个子元素开始计数)
:nth-last-of-type(n)p:nth-last-of-type(2)
:nth-of-type(n)p:nth-of-type(2)
:only-of-typep:only-of-type
:only-childp:only-child 匹配只有一个子元素的p标签
:optionalinput:optional
:out-of-rangeinput:out-of-range
:read-onlyinput:read-only
:read-writeinput:read-write
:requiredinput:required
:root:root 匹配文档的根元素,在HTML中,根元素永远是HTML,可以直接把:root当做html使用
:target#news:target
:validinput:valid
:visiteda:visited
:selection匹配选中(元素中被用户选中或处于高亮状态的部分)
:not()div:not(:nth-child(even)) 匹配不是偶数子元素的div元素

Pseudo Elements(PE)

The :: pseudo represent entities that are not included in HTML.

Example:  p::first-line will match the first line of all <p> elements.

Pseudo Elements 又称伪选择器,用于表示无法用 HTML 语义表达的实体,相当于设置元素制定部分的样式。

选择器例子
::after(:after)div::after{ content:"通过CSS添加文本"; } 用来创建一个伪元素,作为已选中元素的最后一个子元素,这个虚拟元素默认是行内元素
::before(:before)a::before { content: "♥";} Add a heart before links
::-webkit-scrollbar::-webkit-scrollbar{ display:none; } 取消全网页的滚动条样式

CSS 选择器权重

  • CSS选择器解析规则1:当不同选择符的样式设置有冲突的时候,高权重选择符的样式会覆盖低权重选择符的样式
  • CSS选择器解析规则2:相同权重的选择符,样式遵循就近原则,哪个选择符最后定义,就采用哪个选择符样式
选择器权重,CSS中用四位数组表示权重,数字大小本身没有规定,只是代表纬度不同
Type Selector/Pseudo Elements0001
Class Selector/Pseudo Classes/Attribute Selector0010
ID Selector0100
Combinator同类比较,权重求和
Inline Style Sheet1000
!important10000
<head>
    <title>相邻选择器</title>
    <style>
        /*虽然 .father .son 拥有更高的权值,但选择器 p 中的 background 属性被插入了 !important, 
        所以 <p> 的 background 为 red。*/
        p {background: red !important;}
        .father .son {background: blue;}
    </style>
</head>
<body>
    <div class="father">
        <p class="son">test text</p>
    </div>
</body>

See Also

developer.mozilla.org/en-US/docs/…