Web前端入门学习(3)——CSS选择器

2023-05-22,,

CSS选择器

  1. id选择器

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
#box{width:200px;height:200px;border:2px solid #f3f3f3;background:blue;margin:100px auto;}
/* id 选择符 */
</style>
</head>
<body>
<div id="box">我是一个盒子——块状模型</div>
</body>
</html>

 注意:id选择器,在<style>中,在属性名前应加上一个“#”号,代表引用。

2.class选择器

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
.box1{width:200px;height:200px;background:red;}
.box2{border:2px solid #333;background:blue;}
/* class 选择符 */
</style>
</head>
<body>
<div class="box1">我是第一个盒子</div>
<div  class="box2 box1">我是第二个盒子</div>
<div  class="box1">我是第三个盒子,样式跟第一个盒子一样</div>
</body>
</html>

 注意:class选择器,在<style>中,在属性名前应加上一个“.”号,代表引用。

 


  温馨提示:

     id选择器和class选择器的区别:id名称是文档唯一且不可重复出现的,

    class选择器名称是可重复使用的,因此也称为类选择器。

3.标签选择器

 顾名思义,是根据标签名字来进行匹配样式的选择器。

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
p{width:100px;height:100px;background:blue;}
div {width:50px;height:50px;background:red;margin-bottom:10px;}
/* 标签 选择符 */
</style>
</head>
<body>
<div>块</div>
<div>块</div>
<div>块</div>
<p>p1</p>
<p>p1</p>
<p>p1</p>
</body>
</html>

4.群组选择器

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
#box1,#box2,#box3{width:100px; height:100px; background:blue;}
/* 群组  选择符 */
</style>
</head>
<body>
<div id="box1">块</div>
<div id="box2">块</div>
<div id="box3">块</div>
</body>
</html>

5.包含选择器

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
div span p{width:100px; height:100px; background:blue;}
/* 包含  选择符 */
</style>
</head>
<body>
<div>
<p>p1</p>
</div>
<div>
<p>p2</p>
  <span>
  <p>p3</p>
  </span>
</div>
<div>块</div>
<p>p1</p>
<p>p1</p>
<p>p1</p>
</body>
</html>

 不难看出,包含选择器中,只有在div里面的span中的p标签的内容才有变化。

6.通配符

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
*{font:20px/30px;color:#e3e3e3;text-align:center;}
/* 包含  选择符 */
</style>
</head>
<body>
<div>
<p>我是小倩加油站~~</p>
</div>
<div>
<p>哎呦喂</p>
  <span>
  <p>嘿嘿嘿~</p>
  </span>
</div>
<div>干巴爹~</div>
<p>哎呀~</p>
<p>嘻哈~</p>
<p>哟哟~</p>
</body>
</html>

7.选择器优先级

 前面介绍了这么多选择器,接下来该说说这些选择器的优先级,如果在同一文档中出现不同的选择器,应该表现何种样式,于是优先级就诞生了。

 选择器优先级

    标签选择器  <  class选择器  <  id选择器  <  style行间样式 < js


 温馨提示:

    如果同样的选择器出现文档中,默认后者覆盖前者的选择器,则表现为后面选择器的样式。

《Web前端入门学习(3)——CSS选择器.doc》

下载本文的Word格式文档,以方便收藏与打印。