CSS的引入方式共有三種:行內樣式、內部樣式表、外部樣式表。
一、行內樣式
使用style屬性引入CSS樣式。
示例:
<h1 style="color:red;">style屬性的應用</h1><p style="font-size:14px;color:green;">直接在HTML標簽中設置的樣式</p>
實際在寫頁面時不提倡使用,在測試的時候可以使用。
例如:
<!DOCTYPE><html><head> <meta charset="utf-8" /> <title>行內樣式</title></head><body> <!--使用行內樣式引入CSS--> <h1 style="color:red;">Leaping Above The Water</h1> <p style="color:red;font-size:30px;">我是p標簽</p></body></html>
二、內部樣式表
在style標簽中書寫CSS代碼。style標簽寫在head標簽中。
示例:
<head><style type="text/css">h3{color:red;}</style></head>
例如:
<!DOCTYPE><html><head> <meta charset="utf-8" /> <title>內部樣式表</title> <!--使用內部樣式表引入CSS--> <style type="text/css"> div{ background: green; } </style></head><body> <div>我是DIV</div></body></html>
三、外部樣式表
CSS代碼保存在擴展名為.css的樣式表中
HTML文件引用擴展名為.css的樣式表,有兩種方式:鏈接式、導入式。
語法:
1、鏈接式
<link type="text/css" rel="styleSheet" href="CSS文件路徑" />
2、導入式
<style type="text/css">@import url("css文件路徑");</style>
例如:
<!DOCTYPE><html><head> <meta charset="utf-8" /> <title>外部樣式表</title> <!--鏈接式:推薦使用--> <link rel="stylesheet" type="text/css" href="css/style.css" /> <!--導入式--> <style type="text/css"> @import url("css/style.css"); </style></head><body> <ol> <li>1111</li> <li>2222</li> </ol></html>
鏈接式和導入式的區別
<link>
1、屬于XHTML
2、優先加載CSS文件到頁面
@import
1、屬于CSS2.1
2、先加載HTML結構在加載CSS文件。
四、CSS中的優先級
1、樣式優先級
行內樣式>內部樣式>外部樣式(后兩者是就近原則)
例如:
行內樣式和內部樣式比較優先級:
<!DOCTYPE><html><head> <meta charset="utf-8" /> <title>行內樣式和內部樣式表的優先級</title> <!--內部部樣式表--> <style type="text/css"> p{ color: blue; } </style></head><body> <!--行內樣式--> <p style="color: red;">我是p段落</p></html>
瀏覽器運行效果:
結論:行內樣式優先級高于內部樣式表。
內部樣式表和外部樣式表比較優先級:
a、內部樣式表在外部樣式表上面
<!DOCTYPE><html><head> <meta charset="utf-8" /> <title>內部樣式表和外部樣式表的優先級</title> <!--內部部樣式表--> <style type="text/css"> p{ color: blue; } </style> <!--外部樣式表--> <link rel="stylesheet" type="text/css" href="css/style.css" /> </head><body> <p>我是p段落</p> <div>我是div</div> <ol> <li>1111</li> <li>2222</li> </ol></html>
瀏覽器運行效果:
b、外部樣式表在內部樣式表上面
<!DOCTYPE><html><head> <meta charset="utf-8" /> <title>內部樣式表和外部樣式表的優先級</title> <!--外部樣式表--> <link rel="stylesheet" type="text/css" href="css/style.css" /> <!--內部部樣式表--> <style type="text/css"> p{ color: blue; } </style></head><body> <p>我是p段落</p> <div>我是div</div> <ol> <li>1111</li> <li>2222</li> </ol></html>
瀏覽器運行效果:
結論:內部樣式表和外部樣式表使用就近原則,即誰寫在下面以誰為準。
注意:導入式和鏈接式的優先級也是使用就近原則。
2、選擇器優先級
優先級:ID選擇器>類選擇器>標簽選擇器
<!DOCTYPE><html><head> <meta charset="utf-8" /> <title>選擇器的優先級</title> <style type="text/css"> #a{ color: green; } .b{ color: yellow; } h2{ color: red; } </style></head><body> <h2>111</h2> <!--紅色--> <h2 id="a" class="b">222</h2> <!--綠色--> <h2 class="b">333</h2><!--黃色--></html>
瀏覽器運行效果:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答