CSS 选择器
概念
作用:选择页面的某一个或者某一类元素
基本选择器(重点)
1.标签选择器
之前的例子用的就是标签选择器
2.类 选择器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.class1{
color: brown;
}
.class2{
color: aqua;
}
</style>
</head>
<body>
<h1 class="class1">标题1</h1>
<h1 class="class2">标题2</h1>
<h1>标题3</h1>
</body>
</html>
3.id选择器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
/*id 选择器格式
#id名称{}*/
#id1{
color: blue;
}
</style>
</head>
<body>
<h1 id="id1">标题1</h1>
<h1>标题2</h1>
<h1>标题3</h1>
<h1>标题4</h1>
</body>
</html>
层次选择器
1.后代选择器
在某个元素的后面 爷爷 爸爸 你
/*后代选择器 所有p标签以及所有子标签都生效*/
body p{
background: blue;
}
2.子选择器
只有第一次子标签生效
/*子选择器*/
body>p{
background: blue;
}
3.相邻兄弟选择器
就记住是选择他下面的标签就行
4.通用选择器
<style>
.active~p{
background: chartreuse;
}
</style>
向下同级的都影响
结构伪类选择器
简单例子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
/*不使用id 获得标签的第一个元素*/
ul li:first-child{
background: chartreuse;
}
ul li:last-child{
background: darkturquoise;
}
/*选择当前标签的父标签的第x个标签 不考虑类型 这里第一个是h1所以不生效*/
p:nth-child(1){
background: darkorchid;
}
/*选择当前标签的父标签的第x个标签 考虑类型 所以这里是p2生效*/
p:nth-of-type(2){
background: #ff5132;
}
</style>
</head>
<body>
<h1>p0</h1>
<p>p1</p>
<p>p2</p>
<p>p3</p>
<p>p4</p>
<ul>
<li>l1</li>
<li>l2</li>
<li>l3</li>
</ul>
</body>
</html>
属性选择器(推荐使用)
/* =决定等于 *=包含 ^=以这个开头 $=以这个结尾
/*选中a标签所有带id的属性*/
a[id]{
/*去掉下划线*/
text-decoration: none;
}
/*选中a标签id为first的属性*/
a[id=a1]{
text-decoration: none;
}
/*选择id包含b的标签*/
a[id*=b]{
text-decoration: none;
}
/*选择以hhh开头的标签*/
a[id^=hhh]{
text-decoration: none;
}