翻译正在进行中。

接下来,我们将更详细的深入CSS语法,学习属性(peroperties)属性值(value)如何组合成一个声明(declarations), 多个声明构成的声明块(declaration blocks),以及声明块和选择器(selector)构成完整的 CSS 规则(CSS rules)。同时,我们也将介绍一些其他的CSS语法特征,例如注释和空白等,以令我们的介绍更加完整。

前提: 基本的计算机使用能力,已安装基本的软件文件处理的基本知识,以及 HTML 基础 (学习 HTML入门),以及CSS 如何工作的概念。
目标: 详细学习基本的 CSS 语法结构

注意:CSS 是一种声明式语言,这令其语法相当简单直观且易于理解。此外,CSS还有着相当不错的错误修复系统,这一特性允许你犯一些错误但并不会造成什么异常影响 —— 比如,有可能你的某些声明浏览器并不理解,这时浏览器会直接忽略掉这些内容并继续执行渲染。当然这一特性也可能导致一些问题,比如一些异常情况出现的时候,可能在定位问题原因上造成一些障碍。随着阅读的深入,这些优势和缺点都将逐渐清晰。

认识些新名词

从最基本的层次来看,CSS是由两块内容组合而成的:

  • 属性(Properties):一些人类可理解的标识符,这些标识符指出你想修改哪一些样式特征(stylistic features)(例如:font, width, background color) 。
  • 属性值(Values):每个指定的属性都需要给定一个值,这个值表示你想把那些样式特征修改成什么样(例如,你想把字体,宽度或背景颜色改成...)。

一个属性和其对应属性值一起组成的属性/值对被称作一个CSS声明 (CSS declaration). CSS声明会被放置在一个CSS声明块(CSS Declaration Blocks)中。最终,一个CSS声明块与选择器selectors)相结合形成一个CSS规则集(CSS Rulesets 又称 CSS Rules)

在深入那些原理和书面解释之前,让我们先看一个具体的例子(和我们在上篇文章中看的非常相似)

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

以及对应的 CSS 文件:

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

p {
  color: red;
}

p, li {
  text-decoration: underline;
}

两者的结合得到了如下的效果:

让我们来看看语法的更多细节.

CSS 声明(CSS declarations)

给 CSS 属性设置特定的值是 CSS 语言的核心功能。CSS 引擎会通过计算,将对应的 CSS 声明应用到页面的每一个元素上,从而使得元素们以适当的方式布局,并展示出适当的样式。特别需要记住的是,CSS 的属性和属性值都是区分大小写的。属性和属性值之间,用英文半角冒号 (:) 隔离,如下图所示。

CSS 有超过300 个不同的属性以及几乎无穷无尽的属性值。属性和属性值不能任意组合:每个属性都有一个已经定义好的可用属性值范围。 

重要: 如果使用了未知属性,或者给属性赋予了无效值,该声明会被视为无效,浏览器的 CSS 引擎会完全忽略它。

重要: 在 CSS(和其他网络标准)中,使用美式拼写作为单词的标准写法。例如,颜色(见于上述代码所见)应始终拼写为 color。写成 colour 会无法正常工作。

主动学习: 找出声明

在上面的例子里, 有五个独立的CSS声明。你能找出其中无效的声明,并找出它无效的原因吗?

CSS 声明块 (CSS declaration blocks)

声明按 块(blocks)分组,每一组声明都用一对大括号包裹,用 ({) 开始,用 (}结束

声明块 里的每一个声明必须用半角分号(;)分隔,否则代码会不生效(至少不会按预期结果生效)。声明块里的最后一个声明结束的地方,不需要加分号,但是最后加分号是个好习惯,因为可以防止在后续增加声明时忘记加分号。

注意:块有时候是可以嵌套的。这种情况下,每一对括号必须逻辑上嵌套,跟嵌套 HTML 元素的标签嵌套方式相同。最常见的例子是 @-rules,这是一种用 @ 标识开头的块,例如 @media, @font-face等(详见下述的 CSS 语句

注意:声明块的内容允许为空 —— 这完全有效。

主动学习:声明块在哪里?

在上述的例子里,你能找到 三个 独立的 CSS 声明块吗?

CSS 选择器和规则(CSS selectors and rules)

我们的拼图还少了一块——我们需要讨论一下如何告知我们的声明块:哪些元素是它们需要应用的。通过在每个声明块前加上选择器(selector)来完成这一动作,选择器是一种模式(pattern),它能在页面上匹配一些元素这使相关的声明将仅被应用到被选择的元素上。. 选择器加上声明块被称为规则集(ruleset),通常简称规则rule)。

选择器可以很复杂 —— 你可以制作一个匹配多个元素的规则,这是通过把多个选择器囊括成用逗号分隔的选择器(一组,);选择器也可以链接在一起,例如我要选择所有 class 是 "blah" 的元素, 但是当且仅当它在 <article> 元素里、并且仅当鼠标指针悬停在这个元素上的时候。 别担心:随着你在CSS上的经验变的更丰富,事情会变的更清晰。我们将会在下一片文章《Selectors》里,详细地解释选择器。

一个元素可以被多个选择器所匹配,因此,一个给定的属性可能被多个规则设置了多次。 CSS 定义哪个规则比其它规则更具优先级,则更具优先级的必定被应用:这被称为层叠算法(cascade algorithm),关于层叠算法的更多内容和运作原理见《级联和继承》.

Important: If a single basic selector in a chain or group is invalid, like when using an unknown pseudo-element or pseudo-class, the whole group of selectors is invalid and therefore the entire rule is invalid and 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 element?

CSS 语句(CSS statements)

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

White space means actual spaces, tabs and new lines. You can add white space to make your style sheets 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 styleguide 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 recognise padding- 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.

Comments

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. 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 this 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.

What's next

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.

文档标签和贡献者

 最后编辑者: lavenderming,