选择器的作用:用来查找要设置html样式的元素;
css的选择器分为4大类:
1、简单选择器(6种):
1-1:通配符选择器
1-2:标签选择器
1-3:id选择器
1-4:属性选择器
1-5:类选择器
1-6:分组选择器
<!DOCTYPE html>
<html>
<head>
<title>css 学习</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
/* 1、通配符选择器 */
* {
text-decoration: underline;
}
/* 2、标签名选择器 */
h1 {
color: #fff;
}
/* 3、类选择器 */
.h1class {
text-align: center;
}
/* 4、属性选择器 */
h1[id='myh1'] {
text-decoration-color: green;
}
/* 5、id选择器 */
#myh1 {
background-color: darkred;
}
/* 分组选择器 */
h1,
h2 {
border: 6px dotted black;
}
</style>
</head>
<body>
<h1 id="myh1" class="h1class">hello world</h1>
<h2>你好,世界</h2>
</body>
</html>
效果图:
2、组合选择器(4种)(根据他们之间的特定关系来选择html元素)
2-1:后代选择器(空格):选择后代所有的元素
2-2:子选择器(>):直接子元素
2-3:相邻兄弟选择器(+):相同父级,紧随其后的元素
2-4:通用兄弟选择器(~):相同父级,所有同级元素
说明代码:
<!DOCTYPE html>
<html>
<head>
<title>css 学习</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
.box,
.box2,
.box3,
.box4 {
float: left;
margin-left: -2px;
height: 140px;
width: 200px;
border: 2px solid darkred;
font-size: 12px;
}
h6 {
margin: 0;
background: green;
height: 20px;
line-height: 20px;
text-align: center;
color: #fff;
}
/* 后代选择器 */
.box p {
color: green;
}
/* 子选择器 */
.box2>p {
color: green;
}
/* 相邻兄弟选择器 */
.box3>p+p {
color: green;
}
/* 通用兄弟选择器 */
.box4>p~p {
color: green;
}
</style>
</head>
<body>
<div class="box">
<h6>后代选择器</h6>
<p>1、参照元素</p>
<p>2、目标元素</p>
<div>
<p>非直接子元素</p>
</div>
<p>3、非相邻兄弟元素</p>
</div>
<div class="box2">
<h6>子选择器</h6>
<p>1、参照元素</p>
<p>2、目标元素</p>
<div>
<p>非直接子元素</p>
</div>
<p>3、非相邻兄弟元素</p>
</div>
<div class="box3">
<h6>相邻兄弟元素选择器</h6>
<p>1、参照元素</p>
<p>2、目标元素</p>
<div>
<p>非直接子元素</p>
</div>
<p>3、非相邻兄弟元素</p>
</div>
<div class="box4">
<h6>通用兄弟元素选择器</h6>
<p>1、参照元素</p>
<p>2、目标元素</p>
<div>
<p>非直接子元素</p>
</div>
<p>3、非相邻兄弟元素</p>
</div>
</body>
</html>
效果图:
3、伪类选择器(根据HTML元素特定的状态的选择元素,比如:active元素被鼠标按下去、:hover鼠标滑过元素)
4、伪元素选择器(选取元素的一部分并设置样式)