css3之各种选择器

css3中新增的选择器可以简便许多样式。

此次用了属性选择器,root,not,empty,target,first-child,last-child,ntn-child(n),ntn-last-child(n),

first-of-type,nth-of-type(n),last-of-type,nth-last-of-type(n),only-child,only-of-type.

源码如下

<body>
<div id="header">这里是页头</div>
<div id="content">
<ol>
<li><a href="http://...">我是第一个链接</a></li>
<li><a href=".img" class="icon">我是第二个链接</a></li>
<li><a href="#" name="myNameIsThirdBlock">我是第三个链接</a></li>
<li><a id="fourthHref"href="#testTarget" >我是第四个链接</a></li>
<li><a id="testEmpty"></a></li>
<li><a></a></li>
<li><a ></a></li>
<li></li>
</ol>
<p id="testTarget">测试target而已</p>
</div>
<div id="footer">
这里是页尾
</div>
</body>

<style>

/*root根选择器,相当于html*/
:root{
background:#A0F3C2;
}

/*否定选择器,除了id为content之外改变样式*/
div:not([id="content"]){
height:3rem;
margin:20px 0;
color:#97BDEF;
text-align:center;
font-size:1.2rem;
line-height:3rem;
border:.2rem solid #EAA0F3;
}
ol > li{
border:.2rem dotted #ABF7FB;
margin:10%;
}

/*选择父元素的第一个子元素的元素,而不是后代元素

 last-child相似

*/

ol > li:first-child{
font-size:1.5rem;
font-weight:bold;
color:red;
}

/*定位某个父元素的一个或多个特定的子元素

   双数的li 加上阴影

  “n”是参数,可以是正整数值,也可以是表达式

  nth-last-child(n)相似  

*/

ol > li:nth-child(2n){
box-shadow: 10px 10px 5px #888888;

}

/*来控制仅有一个子元素的背景样式*/
ol :only-child{
display:block;
background:#E2ACCA;
}

/*属性选择器 相当于通配符

*E[att^="val"] 属性以val开头的任何字符串

*E[att$="val"] 属性以val结尾的任何字符串

*E[att*="val"] 属性包含val字符串

*

*/
a[href^=http]{
background: pink;
display:block;
color:#fff;
}
a[href$=img]{
background: #F1D182;
display:block;
color: #fff;
}
a[name*=Third]{
background: #CA88E6;
display:block;
color: #fff;
}

/*空选择器*/

a:empty{
display:none;
}
p{
display:none;
}

/*目标选择器,用来匹配文档(页面)的url的某个标志符的目标元素*/

#testTarget:target{
background:yellow;
display:block;
margin:10%;

}
</style>

效果如下:

还有一些选择器就不具体的写了

:enabled

:disabled

:checked

::slelction

:read-only

:read-write

::before ::after

原文地址:https://www.cnblogs.com/fnncat/p/4857461.html