css3选择器一

在HTML中,通过各种各样的属性可以给元素增加很多附加的信息,了解和掌握css3一些的选择器,是很有必要的。

属性选择器示例:
<div><a href="xxx.pdf">我链接的是PDF文件</a>
    <a href="#" class="icon">我类名是icon</a>
    <a href="##" title="this is a box">我的背景想变成蓝色</a>
</div>
<style>
    a[href$=pdf],a[class^=icon],a[title*=this]{color: #fff; padding:10px; text-decoration: none;}

    a[href$=pdf]{
        background: orange;
    }
    a[class^=icon]{
        background: green;
    }
    a[title*=this]{
        background: blue;
    }
</style>
效果图:

结构性伪类选择器

:root 用来设置背景颜色 “:root”选择器和html的效果相同
:root{background:orange}
html {background:orange;}

:not选择器称为否定选择器,可以选择除某个元素之外的所有元素。
input:not([type="submit"]){
border:1px solid red;
}表单中除submit按钮之外的input元素添加红色边框

:empty选择器表示的就是空。用来选择没有任何内容的元素,
p:empty {
border: 1px solid green;
}​ 给空的p元素添加1px的绿色边框。
:target选择器称为目标选择器,用来匹配文档(页面)的url的某个标志符的目标元素。
<div class="menuSection" id="brand">
    content for Brand
</div>
#brand:target{
background: orange; color: #fff;
}

:first-child”选择器表示的是选择父元素的第一个子元素的元素。
ol > li:first-child{
color: red;
}


:first-of-type”其主要用来定位一个父元素下的某个类型的第一个子元素。
.wrapper > p:first-of-type { /*改变第一个段落的背景为橙色*/
background: orange;
}
:last-child”选择器选择的是元素的最后一个子元素。
ul>li:last-child{background:blue;}


:nth-last-child(n)从某父元素的最后一个子元素开始计算,来选择特定的元素。
ol > li:nth-last-child(5){ /*选择列表中倒数第五个列表项,将其背景设置为橙色*/
background: orange;
}
:last-of-type 和  :nth-last-of-type(n) 选择是父元素下的某个类型的最后一个子元素开始计算。
.wrapper > p:last-of-type{  /*将容器“div.wrapper”中最后一个段数的背景设置为橙色*/
background: orange;
}
.wrapper > p:nth-last-of-type(3){/*将容器“div.wrapper”中的倒数第三个段落背景设置为橙色*/
background: orange;
}
 


:nth-child(n)选择器用来定位某个父元素的一个或多个特定的子元素。
其中n是从0开始计算,2n代表偶数,2n+1代表奇数
ol > li:nth-child(2n){  将偶数行列表背景色设置为橙色。
background: orange;
}

:nth-of-type(n)计算父元素中指定的某种类型的子元素
.wrapper > p:nth-of-type(2n){ /*将容器“div.wrapper”中偶数段数的背景设置为橙色*/
background: orange;
}


:only-child 和 :only-of-type 匹配的元素的父元素中仅有一个子元素,而且是一个唯一的子元素。
p:only-child {
background: orange;
}

.wrapper > div:only-of-type {/*修改容器中仅有一个div元素的背景色为橙色*/
background: orange;
}
原文地址:https://www.cnblogs.com/amy-1205/p/5833549.html