【css筆記(2)】如何給元素應用規則?

css選擇器

在介紹以前我麼你先來看看css大體分爲幾種選擇器:css

1.類型選擇器(元素選擇器)html

2.後代選擇器(元素的全部後代)瀏覽器

3.僞類(:active, :hover, :focus, :link, :visited, :first-child, :lang)學習

4.通用選擇器(*)spa

5.子選擇器(元素的直接後代)code

6.相鄰同胞選擇器(同一父元素下該元素以後的某元素)htm

7.屬性選擇器blog

上面講的太抽象?沒事,舉個例子,以下頁面1.html結構:ip

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>1.html</title>
    <style>
        #content div#main-content h2{
            color: gray;
        }
        #content #main-content>h2{
            color: blue;
        }
        body #content div[id="main-content"] h2{
            color: green;
        }
        #main-content div.news-story h2{
            color: orange;
        }
        #main-content [class="news-story"] h2{
            color: yellow;
        }
        div#main-content div.news-story h2.first{
            color: red;
        }
    </style>
</head>
<body>
    <div id="content">
        <div id="main-content">
            <h2>Strange Times</h2>
            <p>Here you can read bizarre news stories from around the globe</p>
            <div class="news-story">
                <h2 class="first">
                    Bog Snorkeling Champion Announced Today
                </h2>
                <p>
                    The 2008 Bog Snorkelinig Championship was won by Conor Murphy with an impressive time of 1 minute 38 seconds
                </p>
            </div>
        </div>
    </div>
</body>
</html>

則對應的選擇器分別有:開發

1.類型選擇器 div{color: red;} 
2.後代選擇器 #content div{background: #ccc;} 
3.僞類 p:first-child{padding: 2px;} 
4.通用選擇器(*) *{margin: 0;} 
5.子選擇器 #content>div{font-size: 14px;} 
6.相鄰同胞選擇器 h2 + p{width: 200px;} 
7.屬性選擇器 div[id="content"]{border: 2px solid #fff;} 

 

css層疊和特殊性

當某一元素應用多種css規則時元素選取那種樣式呢?,css會經過層疊處理這種衝突.層疊會沒每一個規則賦予一個重要度,重要度高的規則會覆蓋重要度低的規則.層疊採用如下重要度次序:

1.標有!important的用戶樣式

2.標有!important的做者(站點開發者)樣式

3.做者(站點開發者)樣式

4.用戶樣式

 

而後經過選擇器的特殊性來決定規則的次序.如何計算特殊性?咱們將選擇器的特殊性由高到低分爲4個等級.應用於下面四個規則:

1.a爲行內樣式(內聯樣式),如有則爲1000,沒有則爲000,a*1000

2.bid選擇器的數量乘100,b*100

3.c爲類,僞類和屬性選擇器的數量乘10,c*10

d爲元素選擇器和僞元素選擇器的數量乘1,d*1

元素的特殊性值(w=a*1000+b*100+c*10+d)後選取特殊性值最大的應用元素

 

咱們還以上面的1.html頁面爲例:

獲得圖中的表,因此應用樣式後的頁面在瀏覽器中顯示爲:

僞類和僞元素

在我剛學習的時候常常講僞類和僞元素搞混,它們是不同的.

僞類

僞類

:active

向被激活的元素添加樣式

:focus

向擁有鍵盤輸入焦點的元素添加樣式

:hover

當鼠標懸浮在元素上方時,向元素添加樣式

:link

向未被訪問的連接添加樣式

:visited

向已被訪問的連接添加樣式

:first-child

向元素的第一個子元素添加樣式

:lang

向帶有指定lang屬性的元素添加樣式

 這是僞元素

僞元素

:first-letter

向文本的第一個字母添加特殊樣式表

:first-line

向文本的首行添加樣式

:before

在元素以前添加內容

:after

在元素以後添加內容

相關文章
相關標籤/搜索