简单来说,层叠样式表(cascading style sheet)是一种专门用来控制界面外观风格的文档。
行内样式
<!doctype html> <html lang="en"> <head> <title>this is title</title> </head> <body> <p style="font-size: 16px; color: red;">my cat is very grumpy</p> </body> </html>
行内样式需要写到标签的 style 属性值中。
内部样式表
<!doctype html> <html lang="en"> <head> <title>this is title</title> <style> p { font-size: 16px; color: red; } </style> </head> <body> <p>my cat is very grumpy</p> </body> </html>
内部样式需要写到
<style>
标签中。
外部样式表
将样式写到单独的文件中,文件的扩展名为 .css
。例如,index.css
文件中有如下样式:
p { font-size: 16px; color: red; }
然后通过 <link>
元素将 index.css
文件引入到页面中:
<!doctype html> <html lang="en"> <head> <title>this is title</title> <link rel="stylesheet" type="text/css" href="./index.css"> </head> <body> <p>my cat is very grumpy</p> </body> </html>
创建 style1.css
文件,文件中有如下样式:
/* style1.css */ h1 { font-size: 32px; color: green; }
创建 style2.css
文件,并使用 @import
指令将 style1.css
导入到 style1.css
文件中:
/* style2.css */ p { font-size: 16px; color: red; }
最后,通过 <link>
元素将 style2.css
文件引入到页面中:
<!doctype html> <html lang="en"> <head> <title>this is title</title> <link rel="stylesheet" type="text/css" href="./style2.css"> </head> <body> <h1>一级标题</h1> <p>my cat is very grumpy</p> </body> </html>
定义在外部文件(外链样式):本教程中案例主要是通过这种形式定义样式。 在页面的头部定义(内联样式):通过这种形式定义的样式只在本页面内生效。 定义在特定的元素身上(行内样式):这种形式多用于测试,可维护性较差。
css 样式由一系列的规则集组成,规则集中有一条或多条样式声明,每条样式声明包含着一对属性名和属性值,属性名和属性值之间以冒号(:
)隔开,样式规则之间以分号(;
)隔开,最后一对样式声明后面可以省略分号。
标签选择器
p { font-size: 16px; color: red; }
选择页面中所有的
<p>
元素,给它们设置字体大小和颜色。
class 选择器
.box { font-size: 20px; color: green; }
选择页面中 class 属性值中包含 box 类名的所有元素,给它们设置字体大小和颜色。
id 选择器
#nav { font-size: 24px; color: blue; }
选择页面中 id 属性值是 nav 的元素,给它设置字体大小和颜色。
通配符选择器
* { font-size: 24px; color: blue; }
行内样式的优先级最高
选择器的优先级根据权重计算
选择器 | id选择器 | class选择器 | 标签选择器 | 总权重 |
---|---|---|---|---|
html body header h1 |
0 | 0 | 4 | 4 |
.page-header .title |
0 | 2 | 0 | 20 |
#page-title |
1 | 0 | 0 | 100 |
属性选择器权重与类相同,
+ > ~
权重为 0
在选择器权重相同的情况下,遵循就近原则,也就是说,谁距离目标元素近,应用哪个个样式。
使用 !important
声明调整样式的优先级
共有三种主要的样式来源:
如对本文有疑问, 点击进行留言回复!!
网友评论