翻譯不完整。請協助 翻譯此英文文件

接下來,我們進一步的深入CSS 語法,觀察如何從屬性和本身的值形成宣告,多個宣告形成宣告區塊,最後宣告區塊及選擇器形成一個完整的 CSS 規則。我們透過觀察其他 CSS 語法功能像是註解和空白來完善此文件。
 

前提:

基本電腦讀寫能力,基本軟體安裝,基本的檔案編輯存取知識,HTML 基礎 (研讀 HTML 介紹),以及 CSS 如何運作的概念。

目標: 學習 CSS 仔細的基礎語法結構

註釋: CSS 是一種宣告式語言,它的語法相當簡單且直覺易於瞭解。另外,它也具有非常好的錯誤回復系統讓你犯錯時不會損毀任何東西 — 舉例:若宣告無法被了解時,一般只會跳過而已。壞處是會難以了解究竟錯誤來自何處。請繼續閱讀,一切最終將會清晰。

詞彙 A touch of vocabulary

在最基礎階段,CSS 考量兩個建構區塊:

  • 屬性 Properties: 人類可讀的識別器用以指出你想要改變何種樣式特徵 (例如:字型、寬度、背景顏色) 。
  • 值 Values: 那些你想要改變的樣式特徵的指定屬性將被賦予值 (例如:你想要改變字型、寬度、背景顏色成為新的值)

一個屬性與一個值配對被稱為一個 CSS 宣告CSS 宣告放置於宣告區塊中。且最終 CSS 宣告區塊又會與選擇器配對產生 CSS 規則組 (或稱為 CSS 規則) 。

在說明或解釋變得更深、更複雜前,讓我們看看一個具體範例 (我們會看到跟上一篇文章相當類似的東西)

<!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>

    <ul>
      <li>This is</li>
      <li>a list</li>
    </ul>
  </body>
</html>

以下是 CSS 檔案:

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

p {
  color: red;
}

p, li {
  text-decoration: underline;
}

組合這兩個檔案後,其結果如下:

語法細節

CSS 宣告

CSS 語言的核心功能是設定賦予 CSS 屬性一個指定值。此 CSS 引擎計算著哪些宣告用以適當的排版及樣式應用於一個頁面中的每個單一元素。請注意記住在 CSS 中這些屬性及值都是大小有別的。 屬性與值使用冒號(:) 分隔。

在 CSS 中大約有超過 300 種不同的屬性,而且有近乎無窮盡的不同設定值。但並非所有的屬性與值的配對都是被允許;每個不同的屬性有一組特定的合法值列表。

重要:假如是未知的屬性或對於賦予的屬性是非法的值時,這個宣告將視為非法且整個被瀏覽器的 CSS 引擎忽略。

重要: 在 CSS (與其他網頁標準),當有不確定發生時,美式拼音已被同意為預設標準,例如:color 應該被拼寫為 color。 colour 則不行。

主動學習:針對宣告

在下方的範例中,有五個分開的 CSS 宣告。你可以區分出那些是非法 (不正確或錯誤) 的宣告而且查出為何這些是非法的呢?

 

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

p {
  color: red;
}

p, li {
  text-decoration: underline;
}

 

CSS 宣告區塊

多個宣告使用區塊來群組化,每一組宣告可由左大括弧 ({) 開始,結束使用右大括弧 (}) 包裹起來。

每一個包含於宣告區塊的宣告必須使用分號 (;) 分隔,否則這些 CSS 碼將不會生效(或會產生不預期的結果)。區塊中最後的宣告不需要一定要使用分號結尾,但加上分號結果通常是一個好的樣式,可用來避免在擴充現有區塊加入新的宣告時忘記加上分號。

Note: Blocks can sometimes be nested; in such cases opening and closing braces must be nested logically, in the same fashion as the tags of nested HTML elements. The most common example you'll come across are @-rules, which are blocks beginning with an @ identifier like @media, @font-face, etc (See CSS Statements below).

Note: A declaration block may be empty — this is perfectly valid.

Active learning: Where are the declaration blocks?

In the above example, have you been able to identify the three separate CSS declaration blocks?

CSS 選擇器與規則

We are missing one part of the puzzle — we need to discuss how to tell our declaration blocks which elements they should be applied to. This is done by prefixing each declaration block with a selector — a pattern that matches some elements on the page. The associated declarations will be applied to those elements only. The selector plus the declaration block is called a ruleset, or often simply just a rule.

Selectors can get very complicated — you can make a rule match multiple elements by including multiple selectors separated by commas (a group,) and selectors can be chained together, for example I want to select any element with a class of "blah", but only if it is inside an <article> element, and only while it is being hovered by the mouse pointer. Don't worry — things will become clearer as you become more experienced with CSS, and we'll explain selectors in great detail in the next article, Selectors.

An element may be matched by several selectors, therefore several rules may set a given property multiple times. CSS defines which one has precedence over the others and must be applied: this is called the cascade algorithm, and you'll learn more about how it works in Cascade and inheritance.

Important: If a single basic selector in a chain or group is invalid, like when using an unknown pseudo-element or pseudo-class, the group of selectors is still valid, except for the invalid selector which will be ignored.

Active learning: Spot the group of selectors

In our example, have you been able to identify the rule that will apply to two different types of elements?

CSS 語句

CSS Rules are the main building blocks of a style sheet — the most common block you'll see in CSS. But there are other types of block that you'll come across occasionally — CSS rules are one type of so-called CSS statements. The other types are as follows:

  • At-rules are used in CSS to convey metadata, conditional information, or other descriptive information. They start with an at sign (@), followed by an identifier to say what kind of rule it is, then a syntax block of some kind, ending with a semi-colon (;). Each type of at-rule, defined by the identifier, will have its own internal syntax and semantics. Examples include: Specific syntax example:
    @import 'custom.css';
    This at-rule imports another CSS file into the current CSS.
  • Nested statements are a specific subset of at-rule, the syntax of which is a nested block of CSS rules that will only be applied to the document if a specific condition is matched:
    • The @media at-rule content is applied only if the device which runs the browser matches the expressed condition;
    • the @supports at-rule content is applied only if the browser actually supports the tested feature;
    • the @document at-rule content is applied only if the current page matches some conditions.
    Specific syntax example:
    @media (min-width: 801px) {
      body {
        margin: 0 auto;
        width: 800px;
      }
    }
    
    The above nested statement only applies the nested rule when the page's width exceeds 800 pixels.

You'll learn more about some types of at-rules/nested statements at appropriate places in the course.

Important: Any statement which isn't a ruleset, an at-rule, or a nested statement is invalid and therefore ignored.

Beyond syntax: make CSS readable

As you can see, CSS syntax is not that hard to write: you write some rules and if you write them wrong, they will just be ignored. However, even if that works, there are some best practices worth knowing to make your CSS code easier to use and maintain.

空白

White space means actual spaces, tabs and new lines. You can add white space to make your stylesheets more readable.

In the same manner as HTML, the browser tends to ignore much of the whitespace inside your CSS; a lot of the whitespace is just there to aid readability. In our first example below we have each declaration (and rule start/end) on its own line — this is arguably a good way to write CSS, as it makes it easy to maintain and understand:

body {
  font: 1em/150% Helvetica, Arial, sans-serif;
  padding: 1em;
  margin: 0 auto;
  max-width: 33em;
}

@media (min-width: 70em) {
  body {
    font-size: 130%;
  }
}

h1 {
  font-size: 1.5em;
}

div p, #id:first-line {
  background-color: red;
  background-style: none
}

div p {
  margin: 0;
  padding: 1em;
}

div p + p {
  padding-top: 0;
}

You could write exactly the same CSS like so, with most of the whitespace removed — this is functionally identical to the first example, but I'm sure you'll agree that it is somewhat harder to read:

body {font: 1em/150% Helvetica, Arial, sans-serif; padding: 1em; margin: 0 auto; max-width: 33em;}
@media (min-width: 70em) { body {font-size: 130%;} }

h1 {font-size: 1.5em;}

div p, #id:first-line {background-color: red; background-style: none}
div p {margin: 0; padding: 1em;}
div p + p {padding-top: 0;}

The code layout you choose is usually a personal preference, although when you start to work in teams, you may find that the existing team has its own style guide that specifies an agreed convention to follow.

The whitespace you do need to be careful of in CSS is the whitespace around the properties and their values. For example, the following is valid CSS:

margin: 0 auto;
padding-left: 10px;

But the following is invalid:

margin: 0auto;
padding- left: 10px;

Because 0auto is not recognised as a valid value for the margin property (0 and auto are two separate values,) and the browser does not recognisepadding- as a valid property. So you should always make sure to separate distinct values from one another by at least a space, but keep property names/values together as one unbroken string.

註釋

As with HTML, you are encouraged to make comments in your CSS, to help you understand how your code works when coming back to it after several months, and to help others understand it. Comments are also useful for temporarily commenting out certain parts of the code for testing purposes, for example if you are trying to find which part of your code is causing an error.

Comments in CSS begin with /* and end with */.

/* Handle basic element styling */
/* -------------------------------------------------------------------------------------------- */
body {font: 1em/150% Helvetica, Arial, sans-serif; padding: 1em; margin: 0 auto; max-width: 33em;}
@media (min-width: 70em) {
  /* Let's special case the global font size. On large screen or window,
     we increase the font size for better readability */
  body {font-size: 130%;}
}

h1 {font-size: 1.5em;}

/* Handle specific elements nested in the DOM  */
/* -------------------------------------------------------------------------------------------- */
div p, #id:first-line {background-color: red; background-style: none}
div p                 {margin          :   0; padding         : 1em;}
div p + p             {padding-top     :   0;                       }

Shorthand

Some properties like font, background, padding, border, and margin are called shorthand properties — this is because they allow you to set several property values in a single line, saving time and making your code neater in the process.

For example, this line:

/* in shorthand like padding and margin, the values are applied
   in the order top, right, bottom, left (the same order as an analog clock). There are also other 
   shorthand types, for example two values, which set for example
   the padding for top/bottom, then left/right */
padding: 10px 15px 15px 5px;

Does the same thing as all these:

padding-top: 10px;
padding-right: 15px;
padding-bottom: 15px;
padding-left: 5px;

Whereas this line:

background: red url(bg-graphic.png) 10px 10px repeat-x fixed;

Does the same thing as all these:

background-color: red;
background-image: url(bg-graphic.png);
background-position: 10px 10px;
background-repeat: repeat-x;
background-scroll: fixed;

We won't attempt to teach these exhaustively — you'll come across many examples later on in the course, and you are advised to look up the shorthand property names in our CSS reference to find out more.

下一步

At this point, you should now understand the fundamentals of CSS syntax necessary to write a working style sheet that's easy to maintain over time. In the next article we will dig deep into CSS selectors, looking at the different ones available and how they work.

 

In this module

 

文件標籤與貢獻者

此頁面的貢獻者: henry1123, mdnwebdocs-bot, freddy50806
最近更新: henry1123,