一、层次选择器
案例结构:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
</style>
</head>
<body>
<p>p1</p>
<p>p2</p>
<p>p3</p>
<ul>
<li>
<p>p4</p>
</li>
<li>
<p>p5</p>
</li>
<li>
<p>p6</p>
</li>
</ul>
</body>
</html>
- 后代选择器:在某个元素的后面
<style>
/*后代选择器*/
body p{
background: aqua;
}
</style>
效果:
- 子选择器
<style>
/*子选择器*/
body > p{
background: #a232be;
}
</style>
效果:
- 相邻兄弟选择器
更改案例代码:
相邻兄弟选择器:
<style>
/*相邻兄弟选择器:只有一个,相邻(向下)*/
.active + p{
background: green;
}
</style>
效果:
- 通用选择器
更改案例代码:
通用选择器:
<style>
/*通用选择器,当前选中元素的向下的所有兄弟元素*/
.active ~ p{
background: green;
}
</style>
效果:
二、结构伪类选择器
案例要用代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
</style>
</head>
<body>
<p>p1</p>
<p>p2</p>
<p>p3</p>
<ul>
<li>li1</li>
<li>li2</li>
<li>li3</li>
</ul>
</body>
</html>
使用一:
<!-- 避免使用 .class , id选择器-->
<style>
/*选中ul的第一个子元素*/
ul li:first-child{
background: #a232be;
}
/*选中ul的最后一个子元素*/
ul li:last-child{
background: green;
}
</style>
效果:
使用二:
<style>
/*选中p1 : 定位到父元素,选择当前的第一个元素
选择当前p元素的父级元素,选中父级元素的第一个,并且是当前元素才生效!
*/
p:nth-child(1){
background: #a232be;
}
</style>
效果:
使用三:
修改案例代码:
使用:
<style>
/*选中p1 : 定位到父元素,选择当前的第一个元素
选择当前p元素的父级元素,选中父级元素的第一个,并且是当前元素才生效!
*/
/*选中父元素,下的p元素的第二个,类型*/
p:nth-of-type(2){
background: green;
}
</style>
效果:
使用四:
同样是使用三的案例代码
使用:
<style>
/*当鼠标移动到h1上时,变换背景颜色*/
h1:hover{
background: #a232be;
}
</style>
效果:
三、属性选择器(常用)
= 绝对等于
*= 包含这个
^= 以什么开头
$= 以什么结尾
案例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.Massimo a{
float: left;
display: block;
height: 50px;
width: 50px;
border-radius: 10px;
background: #a232be;
text-align: center;
color: gainsboro;
text-decoration: none;
margin-right: 5px;
font: bold 20px/50px Arial ;
}
/*存在id属性的元素*/
/*a[id]{*/
/* background: aqua;*/
/*}*/
/*!*id为first的元素*!*/
/*a[id=first]{*/
/* background: green;*/
/*}*/
/*!*class中有links的元素*/
/*= 绝对等于*/
/**= 包含这个元素*/
/**!*/
/*a[class *= links]{*/
/* background: yellow;*/
/*}*/
/*!* 选中href中以https开头的元素*/
/*^= 以这个开头*/
/**!*/
/*a[href^=https]{*/
/* background: aquamarine;*/
/*}*/
/*以pdf结尾的元素
$= 以这个结尾
*/
a[href $= pdf]{
background: red;
}
</style>
</head>
<body>
<p class="Massimo">
<a href="https://www.baidu.com" class="links item first" id="first">1</a>
<a href="" class="links item active" target="_blank" title="test">2</a>
<a href="images/123.html" class="links item">3</a>
<a href="images/123.png" class="links item">4</a>
<a href="images/123.jpg" class="links item">5</a>
<a href="abc" class="links item">6</a>
<a href="/a.pdf" class="links item">7</a>
<a href="/abc.pdf" class="links item">8</a>
<a href="abc.doc" class="links item">9</a>
<a href="abcd.doc" class="links item last">10</a>
</p>
</body>
</html>
效果: