iT邦幫忙

2025 iThome 鐵人賽

DAY 2
0
Modern Web

30天一起搞懂Web觀念系列 第 2

[DAY2] CSS 是什麼?盒模型、選擇器是什麼?

  • 分享至 

  • xImage
  •  

CSS是什麼

CSS(Cascading Style Sheets 階層式樣式表)用來為HTML或XML添加樣式。CSS 不能單獨運作,它必須配合 HTML 或 XML,一起呈現頁面


CSS選擇器、屬性、值

選擇器 {
	屬性:值;
}

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" 屬性的元素
  • color、background、font-weight是屬性(property)
  • 用冒號隔開,指定了color為red、background為yellow則是值(Value)

CSS的權重(css specificity)

就是當疊很多層樣式的時候,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還有一個很重要的條件叫做繼承,就是子元件會繼承父元件的某些屬性,但是自己的屬性(直接選用的)優先於繼承來的屬性,所以不管怎樣他的父親不管權重多高,只要自己已經選了屬性父親的屬性就影響不到他了


CSS盒模型(Box Model)

當瀏覽器在渲染(document) 時,css會把每一個元素視為是一個長方形Box,這個長方形內而外分別是 Content ( 內容 )、Padding ( 內邊距 )、Border ( 邊框 ) 和 Margin ( 外邊距 )

image.png

圖片來源:https://www.geeksforgeeks.org/css/css-box-model/

  • Content:實際內容區域
  • Padding:內容與邊框之間的距離
  • Border:元素的邊框
  • Margin:元素與其他元素的距離

參考資料

https://medium.com/when-you-feel-like-quitting-think-about-why-you/css-權重-css-specificity-6c9160bbd07d

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


上一篇
[DAY1] HTML 是什麼?為什麼是這樣設計?
下一篇
[DAY3] JavaScript是什麼?JS 引擎又是什麼?
系列文
30天一起搞懂Web觀念30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

1
oxxo
iT邦研究生 1 級 ‧ 2025-08-19 11:00:52

看到你分享了我以前的文章 ( 羞 ),最近有寫了新的內容,也分享給你 :)
權重:https://ithelp.ithome.com.tw/articles/10373571
Box Model:https://steam.oxxostudio.tw/category/css/content/element-box-model.html

我要留言

立即登入留言