CSS 入門

在這個主題中,我們將 CSS 套用到一個簡單的 HTML 文件上,在過程中學習這個語言一些實際的東西。

先備知識: 基本的電腦概念、能夠安裝基本軟體,基本與各種檔案打交道的能力,以及 HTML 的基礎(由HTML 入門學到)。
學習目標: 了解將 CSS 文件與 HTML 檔案連接的基本知識,並且能夠使用 CSS 對文字作簡單的格式變化。

由某個 HTML 開始

我們的起點是一個 HTML 文件。如果您想要在自己的電腦上操作,可以把下面的程式碼複製下來。在您電腦上的目錄中,用 index.html 為檔名儲存。

<!doctype html>
<html lang="en">
    <meta charset="utf-8">
    <title>Getting started with CSS</title>


    <h1>I am a level one heading</h1>

    <p>This is a paragraph of text. In the text is a <span>span element</span>
and also a <a href="http://example.com">link</a>.</p>

    <p>This is the second paragraph. It contains an <em>emphasized</em> element.</p>

        <li>Item one</li>
        <li>Item two</li>
        <li>Item <em>three</em></li>





首先,第一個步驟是告訴 HTML 文件我們有些 CSS 規則要加入。你通常有三種不同的方式來將 CSS 套用到 HTML 文件上,然而,現在我們先將焦點放在其中最常見並且實用的方式:在您文件標頭的位置將 CSS 連結進去。

建立一個檔案,存在與您 HTML 文件同一個目錄之中,並命名為 styles.css 。副檔名 .css 會讓它被當作一個 CSS 檔案。

為了連結 styles.cssindex.html 中,在 HTML 文件的 <head> (en-US) 中,加入下面這行:

<link rel="stylesheet" href="styles.css">

<link> (en-US) 元素使用 rel 屬性告訴瀏覽器我們有一個樣式表,接著 href 屬性指向到這個樣式表的位置。您可以在 styles.css 裡加入規則,來測試它是否能夠運作。使用程式碼編輯器,在你的 CSS 檔案中加入下面這段規則:

h1 {
  color: red;

將您的  HTML 與 CSS 檔案儲存後,重新整理瀏覽器裡的頁面。文件中最上頭的第一級標題現在應該會是紅色的。如果是,恭喜!您成功地套到了一些 CSS 設定到 HTML 中了。如果結果不是如此,仔細檢查您的每段文字並確認都輸入正確。

你可以在你電腦裡的 styles.css 上繼續,或是使用我們下的互動編輯器來繼續本教學指引。 互動編輯器的行為,就像是這個 CSS 已經連結到 HTML 中,就如同我們在前面剛剛完成的一樣。

Styling HTML elements

By making our heading red we have already demonstrated that we can target and style an HTML element. We do this by targeting an element selector — this is a selector that directly matches an HTML element name. To target all paragraphs in the document you would use the selector p. To turn all paragraphs green you would use:

p {
  color: green;

You can target multiple selectors at once, by separating the selectors with a comma. If I want all paragraphs and all list items to be green my rule looks like this:

p, li {
    color: green;

Try this out in the interactive editor below (edit the code boxes), or in your local CSS document.


Changing the default behavior of elements

When we look at a well-marked up HTML document, even something as simple as our example, we can see how the browser is making the HTML readable by adding some default styling. Headings are large and bold and our list has bullets. This happens because browsers have internal stylesheets containing default styles, which they apply to all pages by default; without them all of the text would run together in a clump and we would have to style everything from scratch. All modern browsers display HTML content by default in pretty much the same way.

However, you will often want something other than the choice the browser has made. This can be done by simply choosing the HTML element that you want to change, and using a CSS rule to change the way it looks.  A good example is our <ul>, an unordered list. It has list bullets, and if I decide I don't want those bullets I can remove them like so:

li {
  list-style-type: none;

Try adding this to your CSS now.

The list-style-type property is a good property to look at on MDN to see which values are supported. Take a look at the page for list-style-type and you will find an interactive example at the top of the page to try some different values in, then all allowable values are detailed further down the page.

Looking at that page you will discover that in addition to removing the list bullets you can change them — try changing them to square bullets by using a value of square.

Adding a class

So far we have styled elements based on their HTML element names. This works as long as you want all of the elements of that type in your document to look the same. Most of the time that isn't the case and so you will need to find a way to select a subset of the elements without changing the others. The most common way to do this is to add a class to your HTML element and target that class.

In your HTML document, add a class attribute to the second list item. Your list will now look like this:

  <li>Item one</li>
  <li class="special">Item two</li>
  <li>Item <em>three</em></li>

In your CSS you can target the class of special by creating a selector that starts with a full stop character. Add the following to your CSS file:

.special {
  color: orange;
  font-weight: bold;

Save and refresh to see what the result is.

You can apply the class of special to any element on your page that you want to have the same look as this list item. For example, you might want the <span> in the paragraph to also be orange and bold. Try adding a class of special to it, then reload your page and see what happens.

Sometimes you will see rules with a selector that lists the HTML element selector along with the class:

li.special {
  color: orange;
  font-weight: bold;

This syntax means "target any li element that has a class of special". If you were to do this then you would no longer be able to apply the class to a <span> or another element by simply adding the class to it; you would have to add that element to the list of selectors:

span.special {
  color: orange;
  font-weight: bold;

As you can imagine, some classes might be applied to many elements and you don't want to have to keep editing your CSS every time something new needs to take on that style. Therefore it is sometimes best to bypass the element and simply refer to the class, unless you know that you want to create some special rules for one element alone, and perhaps want to make sure they are not applied to other things.

Styling things based on their location in a document

There are times when you will want something to look different based on where it is in the document. There are a number of selectors that can help you here, but for now we will look at just a couple. In our document are two <em> elements — one inside a paragraph and the other inside a list item. To select only an <em> that is nested inside an <li> element I can use a selector called the descendant combinator, which simply takes the form of a space between two other selectors.

Add the following rule to your stylesheet.

li em {
  color: rebeccapurple;

This selector will select any <em> element that is inside (a descendant of) an <li>. So in your example document, you should find that the <em> in the third list item is now purple, but the one inside the paragraph is unchanged.

Something else you might like to try is styling a paragraph when it comes directly after a heading at the same hierarchy level in the HTML. To do so place a +  (an adjacent sibling combinator) between the selectors.

Try adding this rule to your stylesheet as well:

h1 + p {
  font-size: 200%;

The live example below includes the two rules above. Try adding a rule to make a span red, if it is inside a paragraph. You will know if you have it right as the span in the first paragraph will be red, but the one in the first list item will not change color.

Note: As you can see, CSS gives us several ways to target elements, and we've only scratched the surface so far! We will be taking a proper look at all of these selectors and many more in our Selectors articles later on in the course.

Styling things based on state

The final type of styling we shall take a look at in this tutorial is the ability to style things based on their state. A straightforward example of this is when styling links. When we style a link we need to target the <a> (anchor) element. This has different states depending on whether it is unvisited, visited, being hovered over, focused via the keyboard, or in the process of being clicked (activated). You can use CSS to target these different states — the CSS below styles unvisited links pink and visited links green.

a:link {
  color: pink;

a:visited {
  color: green;

You can change the way the link looks when the user hovers over it, for example removing the underline, which is achieved by in the next rule:

a:hover {
  text-decoration: none;

In the live example below, you can play with different values for the various states of a link. I have added the rules above to it, and now realise that the pink color is quite light and hard to read — why not change that to a better color? Can you make the links bold?


We have removed the underline on our link on hover. You could remove the underline from all states of a link. It is worth remembering however that in a real site, you want to ensure that visitors know that a link is a link. Leaving the underline in place, can be an important clue for people to realize that some text inside a paragraph can be clicked on — this is the behavior they are used to. As with everything in CSS, there is the potential to make the document less accessible with your changes — we will aim to highlight potential pitfalls in appropriate places.

Note: you will often see mention of accessibility in these lessons and across MDN. When we talk about accessibility we are referring to the requirement for our webpages to be understandable and usable by everyone.

Your visitor may well be on a computer with a mouse or trackpad, or a phone with a touchscreen. Or they might be using a screenreader, which reads out the content of the document, or they may need to use much larger text, or be navigating the site using the keyboard only.

A plain HTML document is generally accessible to everyone — as you start to style that document it is important that you don't make it less accessible.

Combining selectors and combinators

It is worth noting that you can combine multiple selectors and combinators together. For example:

/* selects any <span> that is inside a <p>, which is inside an <article>  */
article p span { ... }

/* selects any <p> that comes directly after a <ul>, which comes directly after an <h1>  */
h1 + ul + p { ... }

You can combine multiple types together, too. Try adding the following into your code:

body h1 + p .special {
  color: yellow;
  background-color: black;
  padding: 5px;

This will style any element with a class of special, which is inside a <p>, which comes just after an <h1>, which is inside a <body>. Phew!

In the original HTML we provided, the only element styled is <span class="special">.

Don't worry if this seems complicated at the moment — you'll soon start to get the hang of it as you write more CSS.

Wrapping up

In this tutorial, we have taken a look at a number of ways in which you can style a document using CSS. We will be developing this knowledge as we move through the rest of the lessons. However you now already know enough to style text, apply CSS based on different ways of targeting elements in the document, and look up properties and values in the MDN documentation.

In the next lesson we will be taking a look at how CSS is structured.

In this module

  1. What is CSS?
  2. Getting started with CSS
  3. How CSS is structured
  4. How CSS works
  5. Using your new knowledge