css2.5_类选择器
来源:互联网 发布:linux hostname命令 编辑:程序博客网 时间:2024/05/21 07:58
问题引入:
<!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
1 0
- css2.5_类选择器
- css2.6_后代选择器
- css2.7_交集选择器
- css2.09_其他选择器的补充
- css2.08_并集选择器(分组选择器)
- CSS2选择器
- css2选择器写法大全
- CSS选择器大全(CSS2)
- CSS2的选择器
- CSS2-7种选择器
- css2.08_通配符
- CSS2/3选择器详细总结
- web设计人员必读 css2选择器(css2 Selectors)
- css2的几种特殊选择器
- css2.0选择器及文字样式
- HTML5+CSS3自学笔记01-CSS2选择器
- CSS2
- CSS2
- 2 java se(2)----面向对象
- group_concat()函数的应用
- 表单中某些组件值设置不成功的处理
- 网页版微信聊天机器人源码调试遇到的几个问题
- MacOS安装Brew
- css2.5_类选择器
- Web架构师成长之路(转载)
- win10+opencv3.1+CS2013环境搭建
- Git使用问题,最近天天碰到 头疼的 Git 问题 记录
- flex布局实现色子
- iOS10 录音崩溃(设置info.plist)
- 电脑故障——WIN10系统安装浏览器
- eclipse中的Console控制台视图脱离主窗口解决办法
- 进制之间的转换