CSS引入
CSS(cascading style sheet)层叠样式表
- 行间样式
<div style="width:100px; height:100px; background-color:red"> </div>
- 页面级css
<style type="text/css"> </style>
- 外部css文件
//a.html
<head>
<link rel="stylesheet" type="text/css" href="a.css">
</head>
<body>
<div></div>
</body>
// a.css
div{
width:100px;
height:100px;
border-radius:50%;
background-color:black;
}
浏览器会同时加载HTML和CSS,即 "异步加载 "
CSS选择器
1. id选择器
<div id=“only” > 123 </div>
#only{
background-color:red;
}
2. class选择器(类选择器)
<div class=“only” > 123 </div>
.only{
background-color:red;
}
3.标签选择器
<div> 123 </div>
div{
background-color:red;
}
//标签选择器无论被套了多少层都能被选中
4. 通配符选择器
*{
background-color:red
}
//规定所有的样式
5. 属性选择器
[属性名]([属性名=属性值])
{
background-color:red
}
6. 派生选择器(父子选择器)
例如:
div span{
background-color:red;
}
*选择器和选择器之间不一定是同类的选择器成父子关系,也可以多种选择器的组合
例如:.wrapper #box span{
background-color:red;
}
*父子选择器中被选中的元素不一定要是直接的父子关系
例如:
html中:
<div>
<em>1</em>
<strong>
<em>2</em>
</strong>
</div>在css中:
div em {
background-color=red;
}运行结果为1,2都为红色
7. 直接子元素选择器
例如:
div > em{
background-color:red;
}
8. 并列选择器
例如:
HTML中:
<div>1</div>
<div class=“demo”>2</div>
<p class=“demo”>3</p>
在CSS中:
div.demo{
background-color:red;
}
9. 分组选择器
例如:
em,
strong,
span{
background-color:red;
}
10. 伪类选择器
例如:
a: hover{
background-color:red;
}
CSS选择器优先级
!important>行间样式>id=属性选择器>class>标签>通配符
优先级相同的选择器,谁放前面谁就优先被选中
*!important使用规则
例如:div{
background-color:red !important;
}
CSS选择器权重问题
选择器 | 权重值 |
---|---|
!important | Infinity |
行间样式 | 1000 |
id | 100 |
class|属性|伪类 | 10 |
标签|伪元素 | 1 |
通配符 | 0 |
*每个选择器的权重之间是256进制