选择器作用:选择页面上的某一个或者某一类元素
- 基本选择器
- 标签选择器:选择一类标签: 标签{}
- 类选择器 class:选择所有class属性一致的标签,跨标签: .类名{]
- Id选择器:全局唯一! #id名{}
优先级:id > class > 标签
- 层次选择器
- 后代选择器
- 子选择器
- 相邻兄弟选择器
- 通用兄弟选择器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
/*后代选择器*/
body p {
background-color: red;
}
/*子选择器,一代,儿子*/
body>p{
background-color: green;
}
/*相邻兄弟选择器:只有一个(相邻:向下)*/
.active + p {
background-color: aqua;
}
/*通用兄弟选择器,当前选中元素的向下的所有兄弟*/
.active~p{
background-color: black;
}
</style>
</head>
<body>
<p class="active">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>
- 结构伪类选择器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!--结构伪类选择器-->
<style>
/*ul的第一个子元素*/
ul li:first-child{
background-color: red;
}
/*ul的最后一个子元素*/
ul li:last-child{
background-color: green;
}
/*选中p1:定位到父元素,选择当前的第一个元素
选择当前元素的父级元素,选中父级元素的第一个,并且是当前元素才生效
(会被h1标签阻挡)
*/
p:nth-child(1){
background-color: aquamarine;
}
/*选中父元素下的p元素的第二个
(不会被h1标签阻挡)
*/
p:nth-of-type(2){
background-color: bisque;
}
h1:hover{
background: #ff5533;
}
</style>
</head>
<body>
<h1>hello</h1>
<p>p1</p>
<p>p2</p>
<p>p3</p>
<ul>
<li>l1</li>
<li>l2</li>
<li>l3</li>
</ul>
</body>
</html>
- 属性选择器
<style>
/*存在id属性的元素*/
a[id]{
background: #ff5533;
}
/*id=first的元素*/
a[id=first]{
background: aquamarine;
}
/*class中包含links的元素*/
a[class*="links"]{
background: aqua;
}
/*选中href中以http开头的元素*/
a[href^=http]{
background: bisque;
}
/*选中href中以jpg结尾的元素*/
a[href$=jpg]{
background: black;
}
</style>
=是绝对等于
*=是包含
^=是以…开头
$=是以…结尾
这些都是通配符