问题引入:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>类名选择器</title>
<style type="text/css">
p{
color:red;
}
</style>
</head>
<body>
<p>这是段落1</p>
<p>这是段落2</p>
<p>这是段落3</p>
<p>这是段落4</p>
</body>
</html>
浏览器打开的结果是:
css中的类的解析
如果我们需求是段落2以及段落4为绿色,其他段落为红色,这种需求
<style type="text/css">
p{
color:red;
}
</style>
上面的代码实现不了。
有的人会说,我可以通过id选择器来实现,例如:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>类名选择器</title>
<style type="text/css">
p{
color: red;
}
#p1{
color: green;
}
#p2{
color: green;
}
</style>
</head>
<body>
<p>这是段落1</p>
<p id="p1">这是段落2</p>
<p>这是段落3</p>
<p id="p2">这是段落4</p>
</body>
</html>
浏览器查看的结果是:
这样虽然能实现,但是每一处定义个Id效率不高,仔细分析段落2与段落4都是绿色,为啥不选择一个绿色的属性呢?
其实是可以实现的,这就需要类选择器。如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>类名选择器</title>
<style type="text/css">
p{
color: red;
}
.green{
color: green;
}
</style>
</head>
<body>
<p>这是段落1</p>
<p class="green">这是段落2</p>
<p>这是段落3</p>
<p class="green">这是段落4</p>
</body>
</html>
浏览器运行的结果:
所谓的类,就是class属性,class属性和Id非常相识,任何的标签都可以携带class属性
class属性可以重复,比如,页面上可能很多标签都有green这个类
注意:css里面用.表示类
.green{
color: green;
}
同一个标签,可能同时拥有多个类,用空格隔开
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>类名选择器</title>
<style type="text/css">
p{
color: red;
}
.green{
color: green;
}
.underLine{
text-decoration: underline;
}
</style>
</head>
<body>
<p>这是段落1</p>
<p class="green">这是段落2</p>
<p>这是段落3</p>
<p class="green underLine">这是段落4</p>
</body>
</html>
浏览器打开的结果:
注意上面 的class = “green underline”直接一定要有空格
不要写成了下面这种形式
<p class="green" class="underLine"></p>
因为这样p不知道到底选着哪个类,错误 总结:
- class可以重复,也就是说,同一个页面上可能有多个标签同时拥有某一个
- 同一个标签可以同时拥有多个类
- 不要去试图用一个类名,把某个标签的所有样式写完,这个标签要多拥有几个类,共同造成这个标签的样式。
- 每一个类要尽可能小,有“公共”的概念,能够让更多的标签使用
疑惑:id与class如何选择
尽可能的使用class,除非及特殊的情况使用id
原因:id是js用的,js会通过id属性得到标签,所以css层面尽量不用id,
练习:
demo1
demo2
demo3