跳至主要内容

開始探索 CSS 基礎

Adding CSS to our Project with Inline Styles

本單元起講解三個添增 CSS 的方法,首先是內嵌樣式。

在 html 標籤內加入 inline style

格式:style="property: value;"

inline style 範例
<section style="background: red;">
<h1>Get the freedom you deserve.</h1>
</section>
警告

內嵌樣式是不建議使用的方法

Understanding the <style> Tag & Creating a .css File

承上一單元,本單元繼續講解三個添增 CSS 的方法,首先是 Internal CSS(內部樣式)。

在 head 添增 style 標籤(Internal CSS)

Internal CSS 格式
<head>
<!-- 省略其他基本代碼 -->
<style>
CSS-Selector {
property: value;
}
</style>
</head>
Internal CSS 範例
<style>
section {
background: salmon;
}
</style>

在 head 引用 CSS(External CSS)

第三種方法是 External CSS(外部樣式)。 在專案資料夾內建立 .css 檔,並編寫 CSS,然後在 head 標籤內引用 CSS。

External CSS 引用範例
<head>
<!-- 省略其他基本代碼 -->
<link rel="stylesheet" href="./main.css" />
</head>

Applying Additional Styles & Importing Google Fonts

Google Chrome 瀏覽器可設定預設字型。
開啟瀏覽器後,點擊右上方的選單按鈕(三個縱向排列的點),
然後依序點擊:設定 -> 外觀 -> 自訂字型

Google Fonts

Google Fonts

進入 Google Fonts 頁面後,可搜尋字型。
找到滿意的字型後,可點擊畫面右上方的 View selected families 按鈕,
藉以取得引用字型的代碼及 CSS rules。

Theory Time - Selectors

CSS 選擇器大致可分為以下五類,編號愈小優先度愈小。

  1. HTML 標籤,例:h1
  2. Class,例:.blog-post
  3. ID,例:#player1
  4. Universal,例:*
  5. Attributes,例:[disabled]
Attribute 選擇器使用範例
/* 將所有擁有 id 屬性的 color 設為紅色 */
[id] {
color: red;
}

Understanding the "Cascading" Style & Specificity​

本單元解說何謂 CSS Specificity(選擇器的優先順序)
CSS 是 Cascading Style Sheets 的縮寫。 就代碼的編寫順序而言,Cascading 表示樣式的套用是由上而下,
同樣的選擇器若出現多次,最後出現的樣式會蓋過先前出現過的樣式。

Specificity​ 則是影響力大於 Cascading 的要素。
即使編寫順序較早,Specificity 層級較大的樣式仍不會因較晚編寫的規則而失效。

提示

以下解說取自 w3schools。
優先順序的計分規則見此連結:https://www.w3schools.com/css/css_specificity.asp

Specificity Hierarchy

Every CSS selector has its place in the specificity hierarchy.
There are four categories which define the specificity level of a selector:

Inline styles - Example: <h1 style="color: pink;">
IDs - Example: #navbar
Classes, pseudo-classes, attribute selectors - Example: .test, :hover, [href]
Elements and pseudo-elements - Example: h1, ::before

Understanding Inheritance

以 body 標籤當作 CSS 選擇器,可將樣式套用於所有內容,且其優先度低於 Class 選擇器。

Adding Combinators

屬性繼承

CSS 屬性的值可以是 inherit,表示該屬性的值繼承其親元素的值。

inherit 範例
.my-class {
font-family: inherit;
}

Combinator

兩個以上的 CSS 選擇器可以合併為 Combinator(組合器)
Combinator 的 Specificity 計分為選擇器的總和。

CSS 組合器範例
#my-id h1 {
color: blue;
}
Specificity 計算機

Theory Time - Combinators

CSS 組合器可分為四種類型

  • Adjacent Sibling(相鄰同層元素)
  • General Sibling(向後同層元素)
  • Child(子元素)
  • Descendant(後裔元素)
CSS 組合器範例
/* Adjacent Sibling */
s1 + s2... {
property: value;
}

/* General Sibling */
s1 ~ s2... {
property: value;
}

/* Child */
s1 > s2... {
property: value;
}

/* Descendant */
s1 s2... {
property: value;
}

Complete MDN CSS Reference (don't learn this by heart!)

Do you prefer reading? Find written CSS docs on MDN

Common CSS Properties Reference

CSS Combinators

More details on CSS Specifity