CSS (階層式樣式表) 讓你創造出一個好看的網頁,那麼它是如何運作的呢?這篇文章說明了 CSS 是什麼,瀏覽器如何把 HTML 轉換成文件物件模型(DOM),CSS 是如何被應用於 DOM 的各個部份,一些很基本的語法例子,以及在我們的網頁中是如何實際地撰寫這些 CSS。

先修知識: 基本的電腦知識與操作, 基礎軟體安裝, 基本的文件處理知識, 和基本的 HTML 知識 (學習 HTML 入門.)
目標: 學習 CSS 是什麼, 以及如何基本地運用.

什麼是 CSS?

正如我們先前所提,CSS 是一種指定文檔如何呈現給使用者的語言——它們如何地被樣式化,佈局,等等。

文檔通常是使用於標誌語言的文字檔案結構—— HTML 是最常見的標誌語言,但你也能遇到其他的標誌語言,像是 SVG 或 XML

呈現是指把文檔轉換成你的使用者能接受的形式。而瀏覽器,像是 FirefoxChrome 或 IE, 是被設計來把這些文檔視覺化,例如:在電腦螢幕,投影機,或者印表機上面。

CSS 如何影響 HTML?

網頁瀏覽器在文檔應用了 CSS 規則 來影響它們將如何呈現. CSS 規則組成如下:

  • 一組 屬性,屬性的值能更新 HTML 的內容,例如我想要我目前元素的寛是父元素的 50%,且讓它的背景為紅色。
  • 一個 選擇器,它能選擇對你想要更新元素值的元素(們)做更新。 例如:我想運用 CSS 規則到我 HTML 文件的所有段落中。

包含在樣式表中的 CSS 規則決定了網頁的外觀。您將會在該 CSS 語法章節中了解更多關於 CSS 語法的內容 — CSS 語法

一個 CSS 的快速示範

上面劈哩啪啦地說了一堆,可能你有些感覺了,也可能沒什麼感覺。所以咱們快速來做一個實際呈現的範例吧。首先,我們有一個非常簡單的 HTML 文件,它包含了個 <h1> 和一個 <p> (注意到 HTML 使用了一個 <link> 元素來連結樣式表):

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>My CSS experiment</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <h1>Hello World!</h1>
    <p>This is my first CSS example</p>
  </body>
</html>

現在我們來看看包含了兩個 CSS 規則的一個簡單例子:

h1 {
  color: blue;
  background-color: yellow;
  border: 1px solid black;
}

p {
  color: red;
}

第一個看的 CSS 規則它從 h1 選擇器開始,這意味著它的屬性和值將更新給 <h1> 元素。 它包含了三個屬性和相對應的值 (每一組 屬性/值 是被稱為一個宣告):

  1. 第一個宣告是把文字設定為藍色。
  2. 第二個宣告是把背景設定為黃色。
  3. 第三個宣告是把 h1 的邊框 設定成 1 像素寛的實線(不是點線、虛線這之類的)黑色框。

第二個要來看的 CSS 規則,它從 p 選擇器開始,這意味著它的屬性和值將更新給 <p> 元素。它只有一個宣告,設定文字顏色為紅色。

在網頁瀏覽器中,上面的程式碼會輸出如下圖所示:

A simple webpage containing a header of Hello World, and a paragraph that says This is my first CSS example

它看起來並沒有很美觀,但至少它給你了一點點想,讓你對 CSS 是如何地在運作有些了解。

主動學習: 來寫你的第一個 CSS 吧

現在,我們將給你一個機會,讓你嘗試寫寫自己的 CSS。 你可以在下面使用線上即時編輯器,來輸入你的程式碼。與剛剛上面所提到的方法有些類似,你會有一些基本的 HTML 元素,和一些 CSS 屬性。試著為你的 CSS 加入一些簡單的宣告,來美化你的 HTML。

如果你不小心做錯了,沒關係,你可以按下 Reset 按鈕重新開始。如果你卡關了不知該如何下手,你也可以按下 Show  solution 按鈕來看看答案。

How does CSS actually work?

When a browser displays a document, it must combine the document's content with its style information. It processes the document in two stages:

  1. The browser converts HTML and CSS into the DOM (Document Object Model). The DOM represents the document in the computer's memory. It combines the document's content with its style.
  2. The browser displays the contents of the DOM.

About the DOM

A DOM has a tree-like structure. Each element, attribute and piece of text in the markup language becomes a DOM node in the tree structure. The nodes are defined by their relationship to other DOM nodes. Some elements are parents of child nodes, and child nodes have siblings.

Understanding the DOM helps you design, debug and maintain your CSS because the DOM is where your CSS and the document's content meet up.

DOM representation

Rather than a long, boring explanation, let's take an example to see how the DOM and CSS work together.

Let's assume the following HTML code:

<p>
  Let's use:
  <span>Cascading</span>
  <span>Style</span>
  <span>Sheets</span>
</p>

In the DOM, the node corresponding to our <p> element is a parent. Its children are a text node and the nodes corresponding to our <span> elements. The SPAN nodes are also parents, with text nodes as their children:

P
├─ "Let's use:"
├─ SPAN
|  └─ "Cascading"
├─ SPAN
|  └─ "Style"
└─ SPAN
   └─ "Sheets"

This is how a browser interprets the previous HTML snippet —it renders the above DOM tree and then outputs it in the browser like so:

Applying CSS to the DOM

Let's say we added some CSS to our document, to style it. Again, the HTML is as follows:

<p>
  Let's use:
  <span>Cascading</span>
  <span>Style</span>
  <span>Sheets</span>
</p>

If we apply the following CSS to it:

span {
  border: 1px solid black;
  background-color: lime;
}

The browser will parse the HTML and create a DOM from it, then parse the CSS. Since the only rule available in the CSS has a span selector, it will apply that rule to each one of the three spans. The updated output is as follows:

How to apply your CSS to your HTML

There are three different ways to apply CSS to an HTML document that you'll commonly come across, some more useful than others. Here we'll briefly review each one.

External stylesheet

You've already seen external stylesheets in this article, but not by that name. An external stylesheet is when you have your CSS written in a separate file with a .css extension, and you reference it from an HTML <link> element. The HTML file looks something like this:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>My CSS experiment</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <h1>Hello World!</h1>
    <p>This is my first CSS example</p>
  </body>
</html>

And the CSS file:

h1 {
  color: blue;
  background-color: yellow;
  border: 1px solid black;
}

p {
  color: red;
}

This method is arguably the best, as you can use one stylesheet to style multiple documents, and would only need to update the CSS in one place if changes were needed.

Internal stylesheet

An internal stylesheet is where you don't have an external CSS file, but instead place your CSS inside a <style> element, contained inside the HTML head. So the HTML would look like this:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>My CSS experiment</title>
    <style>
      h1 {
        color: blue;
        background-color: yellow;
        border: 1px solid black;
      }

      p {
        color: red;
      }
    </style>
  </head>
  <body>
    <h1>Hello World!</h1>
    <p>This is my first CSS example</p>
  </body>
</html>

This can be useful in some circumstances (maybe you're working with a content management system where you can't modify the CSS files directly), but it isn't quite as efficient as external stylesheets — in a website, the CSS would need to be repeated across every page, and updated in multiple places if changes were required.

Inline styles

Inline styles are CSS declarations that affect one element only, contained within a style attribute:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>My CSS experiment</title>
  </head>
  <body>
    <h1 style="color: blue;background-color: yellow;border: 1px solid black;">Hello World!</h1>
    <p style="color:red;">This is my first CSS example</p>
  </body>
</html>

Please don't do this, unless you really have to! It is really bad for maintenance (you might have to update the same information multiple times per document), and it also mixes your presentational CSS information with your HTML structural information, making the CSS harder to read and understand. Keeping your different types of code separated and pure makes for a much easier job for all who work on the code.

The only time you might have to resort to using inline styles is when your working environment is really restrictive (perhaps your CMS only allows you to edit the HTML body.)

What's next

At this point you should understand the basics of how CSS works, and how browsers deal with it. Next, you'll move on to learn about CSS syntax.

文件標籤與貢獻者

標籤: 
此頁面的貢獻者: jackblackevo, beranemo, iigmir, weichi
最近更新: jackblackevo,