一、CSS概念
- Cascading Style Sheet 层叠样式表
- 表现HTML文件样式的语言,包括对字体、颜色、边距、高度、宽度、背景图片、网页定位等设定
二、基础选择器
1、标签选择器
HTML标签作为标签选择器的名称 ,标签选择器直接应用于HTML标签
<style>
p{
background: yellow;
}
</style>
2、类选择器
类选择器可在页面中多次使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
/*
类选择器
*/
.hello{
background: yellow;
}
</style>
</head>
<body>
<p class="hello">Hello1</p>
<p class="hello">Hello2</p>
</body>
</html>
3、ID选择器
ID具有唯一性,同名的ID选择器在同一个页面中只能使用一次。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
/*
ID选择器
*/
#hello{
background: yellow;
}
</style>
</head>
<body>
<p class="hello" id="hello">Hello1</p>
<p class="hello" id="hello1">Hello2</p>
</body>
</html>
4、基本选择器的优先级
ID选择器 > 类选择器 > 标签选择器 (不遵循就近原则)
三、高级选择器
1、层次选择器
(1) A B 后代选择器
A B 后代选择器,选择匹配的B元素,且匹配的B元素被包含在匹配的A元素内
后代选择器两个选择符之间必须要以空格隔开 e.g. A B
<style>
body p{
background: yellow;
}
</style>
(2) 子选择器
A>B 子选择器,选择匹配的B元素,且匹配的B元素是匹配的A元素的子元素。
<style>
body>p{
background: yellow;
}
</style>
(3) A+B 相邻兄弟选择器
A+B 相邻兄弟选择器,选择匹配的B元素,且匹配的B元素紧位于匹配的A元素后面(向下相邻),若不存在这样的A和B则不会匹配。
<style>
p+h1{
background: YELLOW;
}
</style>
(4) A~B 通用兄弟选择器
A~B 通用兄弟选择器,选择匹配的B元素,且位于匹配的A元素后的所有匹配的B元素
<style>
/*第一个p不会被匹配*/
p~p{
background: yellow;
}
</style>
2、结构伪类选择器
A:first-child 选择父元素A的第一个子元素
<style>
p:first-child{
background: black;
}
</style>
A:last-child 选择父元素A的最后一个子元素
<style>
li:last-child{
background: black;
}
</style>
A B:nth-child(n) 选择父级元素A的第n个子元素B,(n可以是1、2、3),关键字可为even、odd
<style>
body p:nth-child(3){
background: blue;
}
</style>
A:first-of-type 选择父元素内具有指定类型的第一个A元素
<style>
p:first-of-type{
background: black;
}
</style>
A:last-of-type 选择父元素内具有指定类型的最后一个A元素
<style>
p:last-of-type{
background: black;
}
</style>
A B:nth-of-type(n) 选择父元素A内具有指定类型的第n个B元素
<style>
body p:nth-of-type(4){
background: red;
}
</style>
3、属性选择器
A[attr] 选择匹配具有属性attr的A元素,还可多个属性进行选择,只需将属性选择器链接在一起即可。
a[href][title] {color:red;}
A[attr=val] 选择匹配具有属性attr的A元素,并且属性值为val(其中val区分大小 写)
a[id="aaa"]{
background: yellow;
}
A[attr^=val] 选择匹配元素A,且E元素定义了属性attr,其属性值是以val开头的任意字符串
A[attr$=val] 选择匹配元素A,且A元素定义了属性attr,其属性值是以val结尾的任意字符串
A[attr*=val] 选择匹配元素A,且A元素定义了属性attr,其属性值包含了“val”, 即字符串val与属性值中的任意位置相匹配。