HTML Coding with CSS & JavaScript · 中英雙語版
A Bilingual Guidebook

第 1 章:HTML 是骨架 · HTML Is the Structure

HTML 是網頁的骨架,負責內容與結構。

HTML is the skeleton of a webpage, defining its structure and content.

<!DOCTYPE html>
<html lang="zh-Hant">
  <head>
    <meta charset="UTF-8">
    <title>我的第一個網頁</title>
  </head>
  <body>
    <h1>你好,世界!</h1>
    <p>這是我的第一個 HTML 頁面。</p>
  </body>
</html>

中文:<h1> 是標題,<p> 是段落。
English: <h1> is a heading, and <p> is a paragraph.

第 1.1 章:基本語法 · Basic Syntax

HTML 由「標籤」組成,通常是成對出現的(開始與結束標籤)。

HTML consists of "tags," usually appearing in pairs (opening and closing tags).

<tagname>內容 Content</tagname>

第 1.2 章:標題與段落 · Headings & Paragraphs

h1 到 h6 定義標題的重要性,p 則定義一般段落。

h1 to h6 define headings by importance, while p defines paragraphs.

<h1>主標題 Main Heading</h1>
<p>這是一個段落。 This is a paragraph.</p>

第 1.3 章:連結與導航 · Links & Navigation

使用 <a> 標籤創建超連結,href 屬性指定目的地。

Use the <a> tag to create hyperlinks, with the href attribute specifying the destination.

<a href="https://google.com" target="_blank">造訪 Google</a>

第 1.4 章:圖片與多媒體 · Images & Media

圖片標籤是單獨存在的(自閉合),必須包含 src 和 alt 屬性。

Image tags are self-closing and must include src and alt attributes.

<img src="image.jpg" alt="描述文字 Description" width="300">

第 1.5 章:清單列表 · Lists

ul 用於無序清單(點點),ol 用於有序清單(數字)。

ul is for unordered lists (bullets), ol is for ordered lists (numbers).

<ul>
  <li>項目 A</li>
  <li>項目 B</li>
</ul>

第 1.6 章:表格處理 · Tables

表格由 table, tr (列), th (標題), td (單元格) 組成。

Tables consist of table, tr (row), th (header), and td (cell).

<table>
  <tr><th>姓名</th><th>分數</th></tr>
  <tr><td>Alex</td><td>95</td></tr>
</table>

第 1.7 章:表單與輸入 · Forms & Input

表單用於收集用戶數據,input 有多種類型(text, password, checkbox)。

Forms collect user data; input has various types like text, password, etc.

<form>
  <input type="text" placeholder="輸入姓名">
  <button type="submit">提交 Submit</button>
</form>

第 1.8 章:區塊與內聯 · Block vs Inline

區塊元素 (如 div) 佔滿整列;內聯元素 (如 span) 只佔用內容寬度。

Block elements (e.g., div) take full width; Inline elements (e.g., span) take only content width.

<div>我是區塊元素</div>
<span>我是內聯元素</span>

第 1.9 章:語意化標籤 · Semantic HTML

使用語意化標籤(如 header, footer, article)有助於 SEO 與螢幕閱讀器。

Using semantic tags improves SEO and accessibility for screen readers.

<header>頁首</header>
<main>主內容</main>
<footer>頁尾</footer>

第 2 章:CSS 是外觀 · CSS Defines Appearance

CSS 決定網頁的顏色、字型、排版與氣氛。

CSS controls colors, fonts, layout, and the overall visual atmosphere.

h1 {
  color: #1d4ed8;
  font-size: 2rem;
}

p {
  color: #374151;
}

中文:CSS 的基本語法是「選擇器 { 屬性: 值; }」。
English: The basic CSS syntax is “selector { property: value; }”.

第 2.1 章:CSS 選擇器 · Selectors

選擇器決定了樣式要套用到哪個 HTML 元素上。

Selectors determine which HTML elements the styles should be applied to.

/* 標籤選擇器 */ p { color: gray; }
/* Class 選擇器 */ .highlight { color: gold; }
/* ID 選擇器 */ #unique-item { font-weight: bold; }

中文:優先級順序為 ID > Class > Tag。
English: Specificity order is ID > Class > Tag.

第 2.2 章:顏色與字體 · Colors & Fonts

你可以使用顏色名稱、HEX 碼或 RGB 來設定色彩。

You can define colors using names, HEX codes, or RGB values.

body {
  background-color: #0f172a; /* HEX */
  color: rgb(229, 231, 235); /* RGB */
  font-family: sans-serif;
}

第 2.3 章:盒模型 · The Box Model

每個 HTML 元素都是一個矩形盒子,由內到外分別是:內容、內邊距、邊框、外邊距。

Every element is a box consisting of: Content, Padding, Border, and Margin.

.box {
  padding: 20px;   /* 內邊距 */
  border: 2px solid white; /* 邊框 */
  margin: 10px;    /* 外邊距 */
}

第 2.4 章:定位方式 · Positioning

定位讓你可以自由移動元素的位置,甚至是覆蓋在其他元素上方。

Positioning allows you to move elements freely, even overlapping others.

.relative-box { position: relative; top: 10px; }
.absolute-box { position: absolute; right: 0; }
.fixed-nav { position: fixed; top: 0; }

中文:Absolute 定位會參考最近的非 static 父元素。
English: Absolute positioning is relative to its closest non-static ancestor.

第 2.5 章:排版與布局 · CSS Layout (Flexbox)

CSS 不只是改顏色,還負責「元素怎麼排列」。

CSS is not just about colors—it controls how elements are laid out.

Box 1
Box 2
Box 3
.flex-demo {
  display: flex;
  gap: 1rem;
}

.flex-box {
  flex: 1;
}

中文:display: flex 讓元素橫向排列。
English: display: flex lays elements out horizontally.

第 2.6 章:元件化樣式 · CSS Components

CSS 最重要的能力之一,是寫「可以重複使用的樣式」。

One of the most important CSS skills is writing reusable styles.

.demo-button {
  padding: 0.6rem 1.1rem;
  border-radius: 999px;
  font-weight: 600;
}

中文:class 就像積木,可以重複使用。
English: Classes are like building blocks that can be reused.

第 2.7 章:響應式設計 · Responsive Design

網頁必須在手機與桌機上都能正常顯示。

Websites must work well on both mobile and desktop.

@media (max-width: 600px) {
  .flex-demo {
    flex-direction: column;
  }
}

中文:當畫面變小,排版也要跟著改變。
English: Layout should adapt when the screen size changes.

第 2.8 章:CSS 動畫 · Transitions & Keyframes

CSS 動畫讓畫面更有生命感,而且效能比 JavaScript 動畫更好。

CSS animations bring interfaces to life and are more performant than JavaScript animations.

1️⃣ 使用 transition(最常用)

將滑鼠移到我上面 · Hover me
.animate-box {
  transition: transform 0.3s ease;
}

.animate-box:hover {
  transform: translateY(-6px);
}

中文:transition 適合用在「狀態改變」的動畫。
English: transition is best for state-based animations.

2️⃣ 使用 keyframes(重複動畫)

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}

.pulse {
  animation: pulse 1s infinite;
}

中文:@keyframes 適合用在持續或循環動畫。
English: @keyframes is used for continuous or looping animations.

第 2.9 章:JavaScript 觸發動畫 · JS × CSS Animation

JavaScript 本身不負責動畫,而是透過加上 class 來「啟動」CSS 動畫。

JavaScript does not animate directly—it triggers CSS animations by adding classes.

這個區塊的動畫是由 JavaScript 觸發的
This animation is triggered by JavaScript
button.addEventListener('click', () => {
  box.classList.toggle('show');
});

中文:動畫是否播放,取決於 class 是否存在。
English: Whether the animation plays depends on whether the class exists.

第 3 章:JavaScript 是靈魂 · JavaScript Adds Interaction

JavaScript 讓網頁動起來,例如按鈕、動畫、互動內容。

JavaScript brings interactivity to webpages—buttons, animations, dynamic content, and more.

<button id="js-demo-button">點我</button>
<div id="js-demo-output"></div>

<script>
  const button = document.getElementById('js-demo-button');
  const output = document.getElementById('js-demo-output');

  button.addEventListener('click', () => {
    output.textContent = '你觸發了 JavaScript!You triggered JavaScript!';
  });
</script>

第 3.1 章:變數與宣告 · Variables

變數是存放資料的容器。現代 JavaScript 建議使用 let 與 const。

Variables are containers for data. Modern JS uses let and const.

let age = 25;       // 可變動的變數
const name = "Alex"; // 不可變動的常數

第 3.2 章:資料型別 · Data Types

常見的型別包括:字串 (String)、數字 (Number) 與布林值 (Boolean)。

Common types include String, Number, and Boolean.

let isStudent = true;  // Boolean
let price = 100.5;    // Number
let city = "Taipei";  // String

第 3.3 章:算術與比較 · Operators

運算子用於計算數值或比較大小。

Operators are used for calculations and comparisons.

let total = 10 + 5;   // 加法
let isEqual = (5 == 5); // 比較是否相等

第 3.4 章:流程控制 · Control Flow

透過 if...else 判斷條件,讓程式決定執行哪一段程式碼。

Use if...else to let the program decide which code to run.

if (score >= 60) {
  console.log("及格 Pass");
} else {
  console.log("不及格 Fail");
}

第 3.5 章:狀態與切換 · JavaScript State & Toggle

真正的互動不是只有「點一下」,而是「記住目前狀態,並根據狀態改變畫面」。

Real interactivity is not just clicking—it’s about tracking state and updating the UI accordingly.

狀態目前是:關閉 · The state is OFF
<button id="toggle-button">OFF</button>
<div id="toggle-output"></div>

<script>
  let isOn = false;

  const button = document.getElementById('toggle-button');
  const output = document.getElementById('toggle-output');

  button.addEventListener('click', () => {
    isOn = !isOn;

    if (isOn) {
      button.textContent = '關閉 · ON';
      output.textContent = '狀態目前是:開啟 · The state is ON';
    } else {
      button.textContent = '開啟 · OFF';
      output.textContent = '狀態目前是:關閉 · The state is OFF';
    }
  });
</script>

中文:isOn 就是「狀態」,它記住目前是開還是關。
English: isOn is the state—it remembers whether the feature is ON or OFF.

第 3.6 章:class 與動畫 · classList & CSS Animation

在現代前端中,JavaScript 很少直接控制樣式,而是「加上或移除 class」。

In modern frontend development, JavaScript rarely controls styles directly—it adds or removes classes.

這是一個會被 JavaScript 控制的區塊
This box is controlled by JavaScript
<button id="class-toggle-button">Toggle</button>
<div id="animated-box"></div>

<script>
  const button = document.getElementById('class-toggle-button');
  const box = document.getElementById('animated-box');

  button.addEventListener('click', () => {
    box.classList.toggle('active');
  });
</script>

中文:classList.toggle() 會自動判斷要「加上」或「移除」 class。
English: classList.toggle() automatically adds or removes a class.

第 3.7 章:資料產生畫面 · Data → UI

在真實專案中,畫面通常不是寫死的,而是由「資料」產生。

In real projects, UI is usually generated from data, not hard-coded.

<ul id="item-list"></ul>

<script>
  const items = ['HTML', 'CSS', 'JavaScript'];

  const list = document.getElementById('item-list');

  items.forEach(item => {
    const li = document.createElement('li');
    li.textContent = item;
    list.appendChild(li);
  });
</script>

中文:畫面不是一個一個寫,而是由資料自動產生。
English: UI elements are generated from data, not written one by one.

第 3.8 章:除錯與偵錯 · Debugging JavaScript

寫程式不可能一次就對,學會除錯比學會語法更重要。

Code rarely works on the first try—debugging is more important than memorizing syntax.

// 使用 console.log 檢查資料
console.log('Hello Debug');
console.log(items);
console.log(typeof items);

中文:打開瀏覽器的「開發者工具(DevTools)」→ Console。
English: Open DevTools → Console to see log messages.

常見錯誤 1:抓不到元素(null)

const btn = document.getElementById('my-button');
btn.addEventListener('click', () => {
  console.log('clicked');
});

中文:如果 btnnull,代表 HTML 裡根本沒有這個 id。
English: If btn is null, the element does not exist in HTML.

// 安全寫法
const btn = document.getElementById('my-button');

if (btn) {
  btn.addEventListener('click', () => {
    console.log('clicked');
  });
}

常見錯誤 2:Script 放錯位置

<script src="app.js"></script>

中文:如果 script 在 HTML 上面,元素可能還沒出現。
English: If the script runs before HTML is loaded, elements may be null.

建議寫法

<script src="app.js" defer></script>

除錯思考流程(非常重要)

  1. 有沒有 Console Error?
  2. console.log 有沒有印出來?
  3. 資料是不是你以為的樣子?
  4. 元素是不是 null?

中文:錯誤不是壞事,錯誤是你最好的老師。
English: Errors are not failures—they are your best teachers.

第 3.9 章:小型整合元件 · Mini Todo Component

這是一個小型 Todo 元件,整合了前面學到的所有 JavaScript 基礎。

This mini Todo component combines everything you've learned so far.

    const todos = [];
    
    function renderTodos() {
      list.innerHTML = '';
    
      todos.forEach((todo, index) => {
        const li = document.createElement('li');
        li.textContent = todo.text;
    
        if (todo.done) {
          li.classList.add('done');
        }
    
        li.addEventListener('click', () => {
          todos[index].done = !todos[index].done;
          renderTodos();
        });
    
        list.appendChild(li);
      });
    }

    中文:點擊項目即可切換完成狀態。
    English: Click an item to toggle its completed state.

    第 3.10 章:網路請求 · Fetch API

    現代網頁透過 API 與伺服器交換資料,這稱為「非同步處理」。

    Modern web apps exchange data with servers via APIs using Asynchronous JS.

    等待中... Waiting...

    第 3.10 章:非同步與 API · Fetch API

    透過 Fetch,網頁可以在不重新整理的情況下獲取外部資料。

    With Fetch, webpages can retrieve external data without refreshing.

    等待獲取中... Waiting...
    async function getData() {
      const response = await fetch('https://api.quotable.io/random');
      const data = await response.json();
      console.log(data.content);
    }

    第 4 章:學習總結與挑戰任務 · Summary & Challenges

    恭喜你完成本教材!你已經具備撰寫基本前端互動的能力。

    Congratulations! You now have the foundation to build interactive front-end features.

    你已經學會了什麼

    挑戰任務(請自己動手)

    1. 為 Todo 元件加入「刪除」功能
      提示:在 li 裡加一個按鈕
    2. 將 Todo 資料儲存到 localStorage
      提示:JSON.stringify / JSON.parse
    3. 嘗試為完成的項目加入動畫效果
      提示:使用 transition + class
    4. 自行設計一個新的小元件(Tabs / Accordion)

    中文:真正的學習發生在「自己動手修改」的時候。
    English: Real learning happens when you modify the code yourself.

    第 5 章:實戰開發工具 · Modern Developer Tools

    掌握了程式語言後,你需要工具來管理你的代碼並與他人協作。

    After mastering languages, you need tools to manage your code and collaborate.

    第 5.1 章:版本控制 · Git Basics

    Git 就像是程式碼的「時光機」,讓你紀錄每次更動,並在出錯時隨時回溯。

    Git is like a "time machine" for your code, allowing you to record changes and revert if needed.

    # 初始化儲存庫 Initialize a repo
    git init
    
    # 將檔案加入暫存區 Add files to staging
    git add .
    
    # 提交並紀錄版本 Commit changes
    git commit -m "完成第一版教材"
    
    # 查看狀態 Check status
    git status

    💡 **小撇步 Tip:**
    中文:GitHub 是存放 Git 儲存庫最流行的雲端平台。
    English: GitHub is the most popular cloud platform for hosting Git repositories.

    第 5.2 章:發佈網站 · GitHub Pages

    將你的程式碼上傳到 GitHub 後,你可以免費將其啟用為一個正式的網站。

    After uploading code to GitHub, you can enable it as a live website for free.

    🚀 部署步驟:

    1. 在 GitHub 建立一個名為 my-coding-guide 的新儲存庫 (Repository)。
    2. 將你的 Coding.html 改名為 index.html (這很重要,因為這是預設首頁)。
    3. 將檔案上傳 (Push) 到 GitHub。
    4. 進入儲存庫的 Settings > Pages
    5. 在 Branch 選擇 main,然後點擊 Save
    6. 等待幾分鐘,你就會得到一個專屬的網址!
    # 快速部署指令範例
    git remote add origin https://github.com/你的帳號/my-coding-guide.git
    git branch -M main
    git push -u origin main

    💡 **小撇步 Tip:**
    中文:檔案一定要命名為 index.html,GitHub Pages 才能自動識別它為首頁。
    English: You must name your file index.html for GitHub Pages to recognize it as the homepage.

    第 5.3 章:套件管理 · NPM & Packages

    NPM 是 JavaScript 的套件管理工具。它就像是一個「應用程式商店」,你可以下載別人寫好的功能庫 (Library) 到你的專案中使用。

    NPM is a package manager for JS. It’s like an "App Store" where you can download libraries built by other developers.

    # 1. 初始化專案 (產生 package.json)
    npm init -y
    
    # 2. 安裝套件 (例如安裝處理日期的 dayjs)
    npm install dayjs
    
    # 3. 在 JavaScript 中引入使用
    import dayjs from 'dayjs';
    console.log(dayjs().format('YYYY-MM-DD'));

    📦 為什麼要使用套件?

    • 效率: 節省自行開發複雜功能的技術成本。
    • 標準: 使用經過數百萬人測試過的代碼,更安全穩定。
    • 開源: 透過社群協作,持續獲得更新與修正。

    💡 **小撇步 Tip:**
    中文:初學者如果不想安裝 Node.js,也可以透過 CDN (例如 unpkg.com) 直接在 HTML 中用 <script> 引入套件。
    English: Beginners can use CDNs like unpkg.com to include libraries via <script> tags without installing Node.js.

    第 5.4 章:實務應用 · Layout Builder

    當你掌握了基礎後,可以使用「佈局產生器」(Layout Builder) 來快速搭建網頁原型。這是一個整合了編輯器、即時預覽與多種前端工具的開發平台。

    Once you've mastered the basics, use a Layout Builder to rapidly prototype webpages. It integrates editors, live previews, and various frontend tools.

    🛠️ Layout Builder 強大功能:

    🛠️ Layout Builder Powerful Features:

    • 即時預覽: 同時編輯 HTML/CSS/JS 並立即看到結果。
      Live Preview: Edit HTML/CSS/JS simultaneously and see results instantly.
    • 進階組件: 內建圖片裁剪 (Cropper)、文字編輯器 (Quill) 與 代碼高亮 (CodeMirror)。
      Advanced Components: Built-in Cropper, Quill Editor, and CodeMirror highlighting.
    • 一鍵美化: 自動整理混亂的代碼,保持開發整潔。
      One-Click Beautify: Automatically organize messy code to keep development clean.
    • 精靈引導: 內建教學步驟,帶領新手完成第一個佈局。
      Onboarding Wizard: Built-in tutorial steps to guide beginners through their first layout.
    立即體驗 Layout Builder · Try It Now

    💡 **小撇步 Tip:**
    中文:在 Layout Builder 中,你可以練習將第 2.5 章學到的 Flexbox 技巧套用到實際的區塊排版中。
    English: In the Layout Builder, you can practice applying Flexbox skills from Chapter 2.5 to real-world block layouts.