初学CSS
CSS有三种形式,直接添加、页内样式表、独立样式表。
直接添加
<div style="background-color: salmon;">
好好学习,天天向上
</div>
直接在div元素上添加style,这种形式影响范围小,但优先级高。
页内样式表
在head中添加
<head>
<style>
div{
background-color:redbeccapurple;
}
</style>
</head>
优先级中等;影响范围为本页。
独立样式表
先写一个.css文件
在要引用的网页的head中输入
<link rel="stylesheet" href="learn.css">
其中 href后面为.css文件的路径。
这样可以做到一个.css操作多个网页。
优先级与影响范围和页内样式表一致。
※:页内样式表与独立样式表优先级看在html页内的加载顺序,后加载的可以覆盖上面的
绝对路径与相对路径
<!--相对路径-->
<!--learn.css-->
<!--绝对路径-->
<link rel="stylesheet" href="C:\Users\April\Desktop\qingbo/learn.css">
选择器
CSS是由选择器与一条或多条声明构成,而根据选择器不用,又分为几种选择器。
- 元素选择器
div{
background-color;
}
- 类选择器
定义某一类为 class=“class-name”
.class-name{
color:red;
}
- id选择器
前面定义要修改的部分为 id=“xxx”
# xxx{
color:red;
}
- 后代选择器
例在div中加一个ul或者加个其他再加ul。
div ul{
color:red;
}
这个会使div下的所有ul都能被选中并修改样式。
- 子选择器
例在div中加一个ul或者加个其他再加ul。
div > ul {
color:red;
}
子选择器只能使div下一级的ul全部修改样式,而被间隔一级或多级的ul不会有任何修改。
ps:子选择器与后代选择器优先级相同,后加载的会覆盖上面的。
- 分组选择器
div,p,table{
color:red;
}
代表所有的div p table 都能受到影响。
※:用逗号隔开的不一定是元素选择器!!
- 属性选择器
例一个div块的属性设为 name=“xxxx”
[name="xxxx"]{
color:red;
}
优先级
越精确的影响范围越小,但精确度越高。
- id > class
- class > 元素
- id > 元素