一、css选择器的作用:
浏览器通过选择器为满足条件的HTML元素添加CSS样式。
二、css选择器的分类:
css选择器分为:id选择器、类选择器、标签选择器、通配符选择器、后代选择器、分组选择器、相邻兄弟选择器、子元素选择器、属性选择器等。本文着重介绍前六种选择器。
三、具体示例:
1.id、类、标签选择器:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
/*标签选择器:background-color:为body添加背景颜色*/
body{
background-color: azure;
}
/*类选择器:为class名为a的标签添加样式;
* font-size:改变字体大小为36px;
* color:改变字体颜色为cornflowerblue;
* font-family: 改变字体样式为 SWGothe;
*/
.a{
font-size: 36px;
color: cornflowerblue;
font-family: SWGothe;
}
/*id选择器:为id名为b的标签添加样式;
* font-size:改变字体大小为36px;
* color:改变字体颜色为lightblue;
* font-family: 改变字体样式为 SWGothe;
*/
#b{
font-size: 36px;
color: lightblue;
font-family: SWGothe;
}
</style>
</head>
<body>
<span class="a">carpe diem,</span>
<i class="a">seize the day</i>
<p id="b">Be reckless. Live for the moment.</p>
</body>
</html>
2.分组、后代、通配符选择器:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
body{
background-color: azure;
}
/*通配符选择器:为所有的标签添加样式
* font-size:将所有标签中的字体大小设为45px。
*/
*{
font-size: 45px;
font-family: 仿宋;
}
/*分组择器:当有多个被类标识的标签或多个被id标识的标签需要使用相同的样式时,可以使用分组选择器
* color:改变字体颜色为cornflowerblue;
* font-family: 改变字体样式为 SWGothe;
*/
.a,#b{
color: cornflowerblue;
font-family: SWGothe;
}
/*后代选择器:当需要向table标签,form标签中的子标签添加样式时,可以使用该选择器:
* color:设置字体颜色为:cornflowerblue;
* font-family:设置字体样式为:仿宋;
*/
html body a{
color: cornflowerblue;
font-family: 仿宋;
}
</style>
</head>
<body>
<span class="a">carpe diem,</span>
<i class="a">seize the day</i>
<br />
<a>诗酒趁年华</a>
<p id="b">Be reckless. Live for the moment.</p>
<span>别想太多,活在当下。</span>
</body>
</html>