談談 CSS 關鍵字 initial、inherit 和 unset

經常會碰到,問一個 CSS 屬性,例如 position 有多少取值。

通常的回答是 staticrelativeabsolutefixed 。當然,還有一個極少人瞭解的 sticky 。其實,除此之外, CSS 屬性通常還可以設置下面幾個值:

  • initial
  • inherit
  • unset
  • revert
{
  position: initial;
  position: inherit;
  position: unset
 
  /* CSS Cascading and Inheritance Level 4 */
  position: revert;
}

瞭解 CSS 樣式的 initial(默認)和 inherit(繼承)以及 unset 是熟練使用 CSS 的關鍵。(當然由於 revert 未列入規範,本文暫且不過多提及。)

initial

initial關鍵字用於設置 CSS 屬性爲它的默認值,可作用於任何 CSS 樣式。(IE 不支持該關鍵字)

inherit

每一個 CSS 屬性都有一個特性就是,這個屬性必然是默認繼承的 (inherited: Yes) 或者是默認不繼承的 (inherited: no)其中之一,我們可以在 MDN 上通過這個索引查找,判斷一個屬性的是否繼承特性。

可繼承屬性

最後羅列一下默認爲 inherited: Yes 的屬性:

  1. 字體系列屬性
    font: 組合字體
    font-family: 規定元素的字體系列
    font-weight: 設置字體的粗細
    font-size: 設置字體的尺寸
    font-style: 定義字體的風格
    font-variant: 偏大或偏小的字體
  2. 文本系列屬性
    text-indent: 文本縮進
    text-align: 文本水平對劉
    line-height: 行高
    word-spacing: 增加或減少單詞間的空白
    letter-spacing:增加或減少字符間的空白
    text-transform: 控制文本大小寫
    direction: 規定文本的書寫方向
    color: 文本顏色
  3. 元素可見性
    visibility
  4. 表格佈局屬性
    caption-side 定位表格標題位置
    border-collapse 合併表格邊框
    border-spacing 設置相鄰單元格的邊框間的距離
    empty-cells 單元格的邊框的出現與消失
    table-layout 表格的寬度由什麼決定<automatic.fixed.inherit>
  5. 列表佈局屬性
    list-style-type 文字前面的小點點樣式
    list-style-position 小點點位置
    list-style 以上的屬性可通過這屬性集合
  6. 引用
    quotes 設置嵌套引用的引號類型
  7. 光標屬性
    cursor: 箭頭可以變成需要的形狀

unset

名如其意,unset 關鍵字我們可以簡單理解爲不設置。其實,它是關鍵字 initialinherit 的組合。

什麼意思呢?也就是當我們給一個 CSS 屬性設置了 unset 的話:

  1. 如果該屬性是默認繼承屬性,該值等同於 inherit
  2. 如果該屬性是非繼承屬性,該值等同於 initial

舉個例子,根據上面列舉的 CSS 中默認繼承父級樣式的屬性,選取一個,再選取一個不可繼承樣式:

  • 選取一個可繼承樣式: color
  • 選取一個不可繼承樣式: border

看看下面這個簡單的結構:

<div class="father">
    <div class="children">子級元素一</div>
    <div class="children unset">子級元素二</div>
</div>
<style type="text/css">
.father {
    color: red;
    border: 1px solid black;
}
.children {
    color: green;
    border: 1px solid blue;
}
.unset {
    color: unset;
    border: unset;
}
</style>

展示結果:
在這裏插入圖片描述

  • 由於 color 是可繼承樣式,設置了 color: unset 的元素,最終表現爲了父級的顏色 red。
  • 由於 border 是不可繼承樣式,設置了 border: unset 的元素,最終表現爲 border: initial ,也就是默認 border 樣式,無邊框。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章