内联样式 CSS中一共有三种样式,分别是,内联样式,内部样式,外部样式。
内联样式 所谓内联样式,是指直接写在html元素上的样式,通过给html指定style属性,比如下面的代码给h1
设置文本居中。
1 2 3 <body> <h1 style ="text-align: center" > Inline style</h1 > </body>
内部样式 所谓内部样式,是指直接写在<style>
块上的样式,<style>
块一般位于html中的head区块中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <meta name ="viewport" content ="width=device-width,initial-scale=1" /> <meta http-equiv ="content-type" content ="text/html" > <title > Title</title > <style > .parent { display : flex; justify-content : center; align-items : center; width : 800px ; height : 600px ; margin : 0 auto; background-color : #DDDDDD ; } </style > </head > <body > <div class ="parent" > </div > </body > </html >
外部样式 所谓外部样式,是指写在独立的css文件中的样式,然后引入到html文件中供使用。
1 2 3 4 5 6 7 8 9 10 <!DOCTYPE html > <html > <head > <link rel ="stylesheet" type ="text/css" href ="mystyle.css" > </head > <body > <h1 > This is a heading</h1 > <p > This is a paragraph.</p > </body > </html >
这三种样式的优先级如下:
看一个列子,下面这个html包含了以上三种样式
div元素中的内联样式 - 设置文本为蓝色
head/style标签中的内部样式 - 设置文本为绿色
head/link标签中的外部样式 - 设置文本为红色
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <meta name ="viewport" content ="width=device-width,initial-scale=1" /> <meta http-equiv ="content-type" content ="text/html" > <link rel ="stylesheet" type ="text/css" href ="mystyles.css" /> <title > Title</title > <style > .parent { display : flex; justify-content : center; align-items : center; font-size : 30px ; width : 800px ; max-width : 100% ; height : 600px ; margin : 0 auto; color : green; background-color : #DDDDDD ; } </style > </head > <body > <div style ="color: blue" class ="parent" > This is a div</div > </body > </html >
这个页面会显示蓝色字符串:This is a div
.
用Chrome浏览器打开这个html,按键盘上的F12键进入开发者工具,并点击右侧的 Elements
tab,然后点击 Styles
tab,可以看到三种样式。
Styles
标签下依次列出了四种样式,优先级从高到低
element.style - 内联样式,颜色是蓝色,有最高优先级。
.parent - 内部样式,优先级次之
.parent (mystyles.css:1) - 外部样式,优先级再次之
div (user agent stylesheet) - 浏览器默认样式,优先级最低
带删除线的样式(内部样式中的color: green, 和外部样式中的color: red)表示这个样式被覆盖了,有更高优先级的样式抢先了。我们可以将高优先级的样式勾掉(单击样式左侧的checkbox),这样浏览器就会自动应用低优先级的样式。
下图就是把内联样式和内部样式中的color全部勾掉,浏览器就是用了外部样式中的color,文本也就变成了红色。