css高级选择器
1、层次选择器
层次选择器分为 :
- 后代选择器 用空格来表示
- 子选择器 用 > 表示
- 相邻兄弟选择器 用 + 表示
- 通用兄弟选择器 用 ~ 表示
示例代码如下:
<style type="text/css">
p,ul{
border: 1px solid red; /*边框属性*/
}
/*后代选择器*/
/* body p{
background: red;
} */
/*子选择器*/
/* body>p{
background: pink;
} */
/*/!*相邻兄弟选择器*!/*/
/* .active + p{
background: green;
} */
/*/!*通用选择器*!/*/
.active~p{
background: yellow;
}
</style>
<body>
<p class="active">1</p>
<p>2</p>
<p>3</p>
<ul>
<li>
<p>4</p>
</li>
<li>
<p>5</p>
</li>
<li>
<p>6</p>
</li>
</ul>
</body>
2、属性选择器
属性选择器采用的是中括号 [ ] 的形式对页面中的元素进行选择
分为以下几种情况:
其中E表示元素名 attr表示属性名 val表示值
-
E[att] 匹配所有具有att属性的E元素,不考虑它的值
-
E[att=val] 匹配所有att属性等于"val"的E元素
-
E[att *=val] 匹配所有att属性中的值中包含 "val" 的E元素
- E[att ^=val] 匹配所有att属性中的值中以 "val" 开头的E元素
- E[att $=val] 匹配所有att属性中的值中以 "val" 结尾的E元素
<style type="text/css">
/*此段代码只是让结构更美观,后续会详细讲解*/
.demo a {
float: left;
display: block;
height: 50px;
width: 50px;
border-radius: 10px;
text-align: center;
background: #aac;
color: blue;
font: bold 20px/50px Arial;
margin-right: 5px;
text-decoration: none;
margin: 5px;
}
/*存在属性id的元素*/
/* a[id] {
background: yellow;
} */
/*/!*属性id=first的元素*!/*/
/* a[id=first] {
background: red;
} */
/*/!*属性class="links"的元素*!/*/
/* a[class="links"] {
background: red;
} */
/*/!*属性class里包含links字符串的元素*!/*/
/* a[class*=links] {
background: red;
} */
/*/!*属性href里以http开头的元素*!/*/
/* a[href^=http] {
background: red;
} */
/*/!*属性href里以png结尾的元素*!/*/
a[href$=png] {
background: red;
}
</style>
<body>
<p class="demo">
<a href="http://www.baidu.com" class="links item first" id="first" >1</a>
<a href="" class="links active item" title="test website" target="_blank" >2</a>
<a href="sites/file/test.html" class="links item" >3</a>
<a href="sites/file/test.png" class="links item" > 4</a>
<a href="sites/file/image.jpg" class="links item" >5</a>
<a href="efc" class="links item" title="website link" >6</a>
<a href="/a.pdf" class="links item" >7</a>
<a href="/abc.pdf" class="links item" >8</a>
<a href="abcdef.doc" class="links item" >9</a>
<a href="abd.doc" class="linksitem last" id="last">10</a>
</p>
</body>
3、结构伪类选择器
选择器 | 功能描述 | 版本 |
---|---|---|
E:last-child | 选择父元素的倒数第一个子元素E,相当于E:nth-last-child(1) | 3 |
E:nth-child(n) | 选择父元素的第n个子元素,n从1开始计算 | 3 |
E:nth-last-child(n) | 选择父元素的倒数第n个子元素,n从1开始计算 | 3 |
E:first-of-type | 选择父元素下同种标签的第一个元素,相当于E:nth-of-type(1) | 3 |
E:last-of-type | 选择父元素下同种标签的倒数第一个元素,相当于E:nth-last-of-type(1) | 3 |
E:nth-of-type(n) | 与:nth-child(n)作用类似,用作选择使用同种标签的第n个元素 | 3 |
E:nth-last-of-type | 与:nth-last-child作用类似,用作选择同种标签的倒数第一个元素 | 3 |
<style>
li:first-of-type{
background: red;
}
li:last-of-type{
background: blue;
}
/* li:last-child{
background: green;
} */
li:nth-child(3){
background: yellow
}
li:nth-child(3){
background: yellow
}
</style>
<body>
<ul>
<li>我是第1个li元素</li>
<li>我是第2个li元素</li>
<li>我是第3个li元素</li>
<li>我是第4个li元素</li>
<li>我是第5个li元素</li>
<li>我是第6个li元素</li>
</ul>
</body>