CSS(Cascading Style Sheets 階層式樣式表)用來為HTML或XML添加樣式。CSS 不能單獨運作,它必須配合 HTML 或 XML,一起呈現頁面
選擇器 {
屬性:值;
}
h1{
color: blue;
}
.highlight{
color: red;
background: yellow;
font-weight: bold;
}
#footer{
background: white;
}
h1
、 .hightlight
、#footer
分別是三種選擇器(Selector):
以下是一些常見的選擇器:
選擇器類型 | 範例 | 選取目標 |
---|---|---|
通用選擇器 | * |
所有元素 |
元素選擇器 | h1 , p |
指定標籤 |
類別選擇器 | .highlight |
class 屬性為 highlight 的元素 |
ID 選擇器 | #footer |
id 為 footer 的元素(唯一!) |
屬性選擇器 | [type="text"] |
有 type="text" 屬性的元素 |
就是當疊很多層樣式的時候,CSS選擇器的優先權
important! > inline style > ID > Class > Element > *
類型 / 範例 | 說明 | 權重分數 |
---|---|---|
!important |
強制套用樣式(少用,易壞掉整體邏輯) | (1/0/0/0/0)分 |
inline style | 直接寫在 HTML 的 style 屬性中 | (0/1/0/0/0)分 |
ID | #id |
(0/0/1/0/0)分 |
Class / 屬性 / 偽類 | .class 、[attr] 、:hover |
(0/0/0/1/0)分 |
Element / 偽元素 | p , div , ::before |
(0/0/0/0/1)分 |
通用選擇器 | * |
(0/0/0/0/0)分 |
🛑 important! 沒事不要亂用,會不好維護喔!
我們來看一個小題目,以下情況會文字會是什麼顏色?
<div id="intro">
<p class="highlight">
What color is it?
</p>
</div>
div p {
color: blue;
}
.highlight {
color: red;
}
#intro {
color: green; !important
}
你可能會想都有important,那肯定是綠色吧
不是!答案是紅色
因為CSS還有一個很重要的條件叫做繼承,就是子元件會繼承父元件的某些屬性,但是自己的屬性(直接選用的)優先於繼承來的屬性,所以不管怎樣他的父親不管權重多高,只要自己已經選了屬性父親的屬性就影響不到他了
當瀏覽器在渲染(document) 時,css會把每一個元素視為是一個長方形Box,這個長方形內而外分別是 Content ( 內容 )、Padding ( 內邊距 )、Border ( 邊框 ) 和 Margin ( 外邊距 )
圖片來源:https://www.geeksforgeeks.org/css/css-box-model/
https://zh.wikipedia.org/zh-tw/CSS#CSS4
https://www.explainthis.io/zh-hant/swe/css-box-model
https://www.oxxostudio.tw/articles/202008/css-box-model.html
https://ithelp.ithome.com.tw/m/articles/10269959
看到你分享了我以前的文章 ( 羞 ),最近有寫了新的內容,也分享給你 :)
權重:https://ithelp.ithome.com.tw/articles/10373571
Box Model:https://steam.oxxostudio.tw/category/css/content/element-box-model.html