一、简介
层叠样式表,css可以用来为网页创建样式表,通过样式表可以对网页进行装饰,所谓层叠就是可以将网页想象成一层一层的结构,层次高的将会覆盖层次低的,而css就可以分别为网页的各个层次设置样式。
二、样式
1. 内联样式
将样式直接写到style属性中,内联样式只对当前元素的内容起作用
(1) 示例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>静夜思</title>
</head>
<body>
<h1 style="color:red; font-size:50px; text-align: center;"> 静夜思 </h1>
<h2 style="color:red; font-size:30px; text-align: center;"> --李白 </h2>
<p style="color:red; font-size:40px; text-align: center;">床前明月光,疑似地上霜。</p>
<p style="color:red; font-size:40px; text-align: center;">举头思故乡,低头望明月。</p>
</body>
</html>
注意:内联样式属于结构表现耦合,不方便后期维护,不推荐使用
2. 内部样式
将css的样式编写到head中的style标签中,通过css选择器选中指定元素,然后同时为这一些元素设置样式,使表现和结构进一步分离。
(1) 示例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>静夜思</title>
<style type="text/css">
p {
color:red;
font-size:40px;
text-align: center;
}
h1 {
color:red; font-size:50px; text-align: center;
}
h2 {
color:red; font-size:30px; text-align: center;
}
</style>
</head>
<body>
<h1> 静夜思 </h1>
<h2> --李白 </h2>
<p>床前明月光,疑似地上霜。</p>
<p>举头思故乡,低头望明月。</p>
</body>
</html>
注意:内部样式只对本页有效
3. 外部样式
将样式编写到外部的css样式中,然后通过link标签来讲外部的css文件导入到当前页面中
(1) 示例
css/style.css
p {
color:red;
font-size:40px;
text-align: center;
}
h1 {
color:red; font-size:50px; text-align: center;
}
h2 {
color:red; font-size:30px; text-align: center;
}
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>静夜思</title>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
</head>
<body>
<h1> 静夜思 </h1>
<h2> --李白 </h2>
<p>床前明月光,疑似地上霜。</p>
<p>举头思故乡,低头望明月。</p>
</body>
</html>
注意:将css文件写到外部的样式表中,完全使结构和表现分离,最大限度的是样式可以在不同的页面中复用,然后通过link标签引入,可以利用浏览器的缓存,加快用户访问速度
三、语法
1. 选择器
通过选择器可以选中页面指定的元素,并且将声明块中的样式应用到选择器对应的样式中
1.1 元素选择器
p {
color:red;
font-size:50px;
text-align: center;
}
<p>床前明月光,疑似地上霜。</p>
1.2 id选择器
#p1 {
color:red;
font-size:40px;
text-align: center;
}
<p id="p1">床前明月光,疑似地上霜。</p>
注意:id不可以重复
1.3 类选择器
.p2 {
color:red;
font-size:40px;
text-align: center;
}
<p class="p2">床前明月光,疑似地上霜。</p>
<p class="p2">举头思故乡,低头望明月。</p>
注意:可以同时为一个元素设置多个class,例:
<p class="p2 test">床前明月光,疑似地上霜。</p>
1.4 选择器分组
#p1, .p2, h1, h2 {
color:red;
font-size:40px;
text-align: center;
}
1.5 通配选择器
* {
color:red;
font-size:40px;
text-align: center;
}
1.6 复合选择器(交集选择器)
选中满足多个选择器的元素(同时满足h p1)
h.p1 {
color:red;
font-size:40px;
text-align: center;
}
1.7~1.8
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>选择器</title>
</head>
<body>
<div>
<span>div->span</span>
<p><span>p->span</span></p>
</div>
<div>
<span>div->span</span>
</div>
</body>
</html>
1.7 后代选择器 div下所有的的span
div span {
color:red;
text-align: center;
}
1.8 子元素选择器
div > span {
color:red;
text-align: center;
}
2. 声明块
声明块紧跟在选择器的后面,使用一对{}括起来,声明块中实际上是一组一组值对结构,声明的样式名和样式值用:来连接,多组声明用;隔开