css的優先順序

來源:互聯網
上載者:User

標籤:style   class   blog   code   java   http   

網頁開發中遇到不少次關於樣式另類的問題,於是想把從網上找的文章和自己想到的做一個簡單的規整。

在此推薦文章:http://www.cnblogs.com/ccdc/p/2765827.html

原則一:內嵌樣式->內部樣式->外聯樣式,優先順序依次排列

  如果外聯樣式放在內部樣式後,將會覆蓋內部樣式。

ex:

<html>    <head>        <title>css優先順序</title>        <style type="text/css">            .priority {color: #00ff00;}        </style>    </head>    <body>        <div class="priority">公告</div>    </body></html><link rel="stylesheet" type="text/css" href="/Content/priority.css"><!--color:#ff0000;-->

結果:

公告

原則二:明確指定添加樣式的元素,使有層次

ex:

<html><head>    <title>css優先順序</title>    <style type="text/css">        div p span.priority {color: #00ff00;}/*1*/        .priority {color: #ff0000;}/*2*/    </style></head>    <body>        <div ><p><span class="priority">公告</span></p></div>    </body></html>

結果:寫法1要優先於寫法2。

公告

 

原則三:css選取器特性

css選取器 特性值
id選取器:# 100
className:. 10
html標記:span 1


原則二中的例子也可以這樣解釋:寫法1選取器的特性值為1+1+1+10=13,寫法1選取器的特性值為10。很明顯根據特性值的大小

可以決定寫法1要優先於寫法2。

原則四:!important

  在一組樣式表中,如果樣式有聲明!important,表示優先順序高。

ex:

<html>    <head>        <title>css優先順序</title>        <style type="text/css">            .priority {color: #ff0000;color: #0000ff !important;}    </style>    </head>    <body>        <div ><p><span class="priority">公告</span></p></div>    </body></html>

體現這四個原則的例子在IE7~9,chrome,firefox,safari,搜狗,360瀏覽器都支援

五:@import
寫到這順便提一下@import ,@import與link的區別在於:@import先載入頁面再載入樣式表,link先載入樣式表再載入頁面。所以在網速慢的情況下

如果使用@import載入頁面時會出現跑版的瞬間。

@import只能載入樣式表,不能像link一樣添加rel,style等屬性。

個人不建議使用@import

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.