CSS FAQ

在本文中,你将找到一些有关 CSS 的常见问题 (FAQ),以及可能有助于你成为 Web 开发者的答案。

¥In this article, you'll find some frequently-asked questions (FAQs) about CSS, along with answers that may help you on your quest to become a web developer.

为什么我的 CSS 有效,却无法正确渲染?

¥Why doesn't my CSS, which is valid, render correctly?

浏览器使用 DOCTYPE 声明来选择是否使用与 Web 标准或旧浏览器错误更兼容的模式来显示文档。在 HTML 开头使用正确且现代的 DOCTYPE 声明将提高浏览器标准合规性。

¥Browsers use the DOCTYPE declaration to choose whether to show the document using a mode that is more compatible with Web standards or with old browser bugs. Using a correct and modern DOCTYPE declaration at the start of your HTML will improve browser standards compliance.

现代浏览器有两种主要的渲染模式:

¥Modern browsers have two main rendering modes:

  • 怪癖模式:也称为向后兼容模式,允许旧版网页按照其作者的意图呈现,遵循旧浏览器使用的非标准呈现规则。具有不完整、不正确或缺失的 DOCTYPE 声明或 2001 年之前常用的已知 DOCTYPE 声明的文档将以 Quirks 模式呈现。
  • 标准模式:该浏览器尝试严格遵循 W3C 标准。新的 HTML 页面预计将针对符合标准的浏览器进行设计,因此,具有现代 DOCTYPE 声明的页面将使用标准模式呈现。

基于 Gecko 的浏览器有第三个 有限的怪癖模式,它只有一些小怪癖。

¥Gecko-based browsers have a third limited quirks mode that has only a few minor quirks.

将触发标准模式的标准 DOCTYPE 声明是:

¥The standard DOCTYPE declaration that will trigger standards mode is:

html
<!doctype html>

如果可能的话,你应该只使用上面的文档类型。还有其他有效的旧文档类型将触发标准或几乎标准模式:

¥When at all possible, you should just use the above doctype. There are other valid legacy doctypes that will trigger Standards or Almost Standards mode:

html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

为什么我的 CSS(有效)根本不渲染?

¥Why doesn't my CSS, which is valid, render at all?

以下是一些可能的原因:

¥Here are some possible causes:

  • CSS 文件的路径错误。
  • 要应用 CSS 样式表,必须使用 text/css MIME 类型。如果 Web 服务器不提供此类型,则不会应用它。

idclass 有什么区别?

¥What is the difference between id and class?

HTML 元素可以具有 id 和/或 class 属性。id 属性为其应用的元素分配一个名称,对于有效标记,只能有一个具有该名称的元素。class 属性为元素分配一个类名称,并且该名称可以在页面内的许多元素上使用。CSS 允许你将样式应用于特定的 id 和/或 class 名称。

¥HTML elements can have an id and/or class attribute. The id attribute assigns a name to the element it is applied to, and for valid markup, there can be only one element with that name. The class attribute assigns a class name to the element, and that name can be used on many elements within the page. CSS allows you to apply styles to particular id and/or class names.

  • 当你想要将样式规则应用于页面中的许多块和元素时,或者当你当前只有使用该样式设置样式的元素,但你可能希望稍后添加更多时,请使用特定于类的样式。
  • 当你需要将应用的样式规则限制到一个特定的块或元素时,请使用特定于 id 的样式。此样式仅由具有该特定 id 的元素使用。

通常建议尽可能多地使用类,并且仅在特定用途绝对必要时才使用 ids(例如连接标签和表单元素或用于语义上必须唯一的样式元素):

¥It is generally recommended to use classes as much as possible, and to use ids only when absolutely necessary for specific uses (like to connect label and form elements or for styling elements that must be semantically unique):

  • 使用类可以使你的样式可扩展 - 即使你现在只有一个元素可以使用特定规则集进行样式设置,你也可能希望稍后添加更多元素。
  • 类允许你设置多个元素的样式,因此它们可以缩短样式表,而不必在使用 id 选择器的多个规则中写出相同的样式信息。较短的样式表性能更高。
  • 类选择器的 specificity 低于 id 选择器,因此在需要时更容易覆盖。

注意:请参阅 选择器 了解更多信息。

¥Note: See Selectors for more information.

如何恢复属性的默认值?

¥How do I restore the default value of a property?

最初 CSS 没有提供 "default" 关键字,恢复属性默认值的唯一方法是显式重新声明该属性。例如:

¥Initially CSS didn't provide a "default" keyword and the only way to restore the default value of a property is to explicitly re-declare that property. For example:

css
/* Heading default color is black */
h1 {
  color: red;
}
h1 {
  color: black;
}

CSS 2 改变了这一点;关键字 initial 现在是 CSS 属性的有效值。它将其重置为默认值,该值在给定属性的 CSS 规范中定义。

¥This has changed with CSS 2; the keyword initial is now a valid value for a CSS property. It resets it to its default value, which is defined in the CSS specification of the given property.

css
/* Heading default color is black */
h1 {
  color: red;
}
h1 {
  color: initial;
}

如何从一种风格衍生另一种风格?

¥How do I derive one style from another?

CSS 并不完全允许用一种样式来定义另一种样式。然而,将多个类分配给单个元素可以提供相同的效果,并且 CSS 变量 现在提供了一种在一个地方定义样式信息的方法,该信息可以在多个地方重用。

¥CSS does not exactly allow one style to be defined in terms of another. However, assigning multiple classes to a single element can provide the same effect, and CSS Variables now provide a way to define style information in one place that can be reused in multiple places.

如何为一个元素分配多个类?

¥How do I assign multiple classes to an element?

HTML 元素可以通过在 class 属性中列出类来分配多个类,并用空格分隔它们。

¥HTML elements can be assigned multiple classes by listing the classes in the class attribute, with a blank space to separate them.

html
<style>
  .news {
    background: black;
    color: white;
  }
  .today {
    font-weight: bold;
  }
</style>

<div class="news today">Content of today's news goes here.</div>

如果两个规则中声明了相同的属性,则首先通过特殊性解决冲突,然后根据 CSS 声明的顺序解决冲突。class 属性中的类顺序不相关。

¥If the same property is declared in both rules, the conflict is resolved first through specificity, then according to the order of the CSS declarations. The order of classes in the class attribute is not relevant.

为什么我的样式规则不能正常工作?

¥Why don't my style rules work properly?

语法上正确的样式规则可能不适用于某些情况。你可以使用检查器 CSS 窗格的 规则视图 来调试此类问题,但下面列出了忽略样式规则的最常见实例。

¥Style rules that are syntactically correct may not apply in certain situations. You can use Rules view of CSS Pane of the Inspector to debug problems of this kind, but the most frequent instances of ignored style rules are listed below.

HTML 元素层次结构

¥HTML elements hierarchy

CSS 样式应用于 HTML 元素的方式还取决于元素的层次结构。重要的是要记住,无论 CSS 规则有任何特殊性或优先级,应用于后代的规则都会覆盖父级的样式。

¥The way CSS styles are applied to HTML elements depends also on the elements' hierarchy. It is important to remember that a rule applied to a descendant overrides the style of the parent, in spite of any specificity or priority of CSS rules.

css
.news {
  color: black;
}
.corpName {
  font-weight: bold;
  color: red;
}
html
<!-- news item text is black, but corporate name is red and in bold -->
<div class="news">
  (Reuters) <span class="corpName">General Electric</span> (GE.NYS) announced on
  Thursday…
</div>

在复杂的 HTML 层次结构的情况下,如果规则似乎被忽略,请检查该元素是否位于具有不同样式的另一个元素内。

¥In case of complex HTML hierarchies, if a rule seems to be ignored, check if the element is inside another element with a different style.

显式重新定义样式规则

¥Explicitly re-defined style rule

在 CSS 样式表中,顺序很重要。如果你定义了一个规则,然后重新定义了相同的规则,则将使用最后一个定义。

¥In CSS stylesheets, order is important. If you define a rule and then you re-define the same rule, the last definition is used.

css
#stockTicker {
  font-weight: bold;
}
.stockSymbol {
  color: red;
}
/*  other rules             */
/*  other rules             */
/*  other rules             */
.stockSymbol {
  font-weight: normal;
}
html
<!-- most text is in bold, except "GE", which is red and not bold -->
<div id="stockTicker">NYS: <span class="stockSymbol">GE</span> +1.0…</div>

为了避免这种错误,请尝试为某个选择器仅定义一次规则,并将属于该选择器的所有规则分组。

¥To avoid this kind of error, try to define rules only once for a certain selector, and group all rules belonging to that selector.

使用简写属性

¥Use of a shorthand property

使用速记属性来定义样式规则很好,因为它使用非常紧凑的语法。仅对某些属性使用简写是可能且正确的,但必须记住,未声明的属性会自动重置为其默认值。这意味着单个属性的先前规则可能会被隐式覆盖。

¥Using shorthand properties for defining style rules is good because it uses a very compact syntax. Using shorthand with only some attributes is possible and correct, but it must be remembered that undeclared attributes are automatically reset to their default values. This means that a previous rule for a single attribute could be implicitly overridden.

css
#stockTicker {
  font-size: 12px;
  font-family: Verdana;
  font-weight: bold;
}
.stockSymbol {
  font: 14px Arial;
  color: red;
}
html
<div id="stockTicker">NYS: <span class="stockSymbol">GE</span> +1.0…</div>

在前面的示例中,问题发生在属于不同元素的规则上,但也可能发生在同一元素上,因为规则顺序很重要。

¥In the previous example the problem occurred on rules belonging to different elements, but it could happen also for the same element, because rule order is important.

css
#stockTicker {
  font-weight: bold;
  font: 12px Verdana; /* font-weight is now set to normal */
}

* 选择器的使用

¥Use of the * selector

* 通配符选择器引用任何元素,使用时必须特别小心。

¥The * wildcard selector refers to any element, and it has to be used with particular care.

css
body * {
  font-weight: normal;
}
#stockTicker {
  font: 12px Verdana;
}
.corpName {
  font-weight: bold;
}
.stockUp {
  color: red;
}
html
<div id="section">
  NYS: <span class="corpName"><span class="stockUp">GE</span></span> +1.0…
</div>

在此示例中,body * 选择器将规则应用于 body 内任何层次结构级别的所有元素,包括 .stockUp 类。因此,应用于 .corpName 类的 font-weight: bold; 被应用于正文中所有元素的 font-weight: normal; 覆盖。

¥In this example the body * selector applies the rule to all elements inside body, at any hierarchy level, including the .stockUp class. So font-weight: bold; applied to the .corpName class is overridden by font-weight: normal; applied to all elements in the body.

应尽量减少 * 选择器的使用,因为它是一个缓慢的选择器,特别是当不用作选择器的第一个元素时。应尽可能避免使用它。

¥The use of the * selector should be minimized as it is a slow selector, especially when not used as the first element of a selector. Its use should be avoided as much as possible.

CSS 的特殊性

¥Specificity in CSS

当多个规则应用于某个元素时,所选择的规则取决于其样式 specificity。内联样式(在 HTML style 属性中)具有最高的特异性,将覆盖任何选择器,其次是 ID 选择器,然后是类选择器,最后是元素选择器。因此,下面的 <div> 的文本颜色将为红色。

¥When multiple rules apply to a certain element, the rule chosen depends on its style specificity. Inline style (in HTML style attributes) has the highest specificity and will override any selectors, followed by ID selectors, then class selectors, and eventually element selectors. The text color of the below <div> will therefore be red.

css
div {
  color: black;
}
#orange {
  color: orange;
}
.green {
  color: green;
}
html
<div id="orange" class="green" style="color: red;">This is red</div>

当选择器有多个部分时,规则会更加复杂。有关如何计算选择器特异性的更详细说明可以在 CSS 特殊性文档

¥The rules are more complicated when the selector has multiple parts. A more detailed explanation about how selector specificity is calculated can be found in the CSS specificity documentation.

-moz-、-ms-、-webkit-、-o- 和 -khtml-* 属性有什么作用?

¥What do the -moz-*, -ms-*, -webkit-*, -o-* and -khtml-* properties do?

这些属性称为前缀属性,是 CSS 标准的扩展。它们曾经被用来允许在浏览器中使用实验性和非标准功能,而不会污染常规名称空间,从而防止未来扩展标准时出现不兼容问题。

¥These properties, called prefixed properties, are extensions to the CSS standard. They were once used to allow the use of experimental and non-standard features in browsers without polluting the regular namespace, preventing future incompatibilities to arise when the standard is extended.

不建议在生产网站上使用此类属性 - 它们已经造成了巨大的网络兼容性混乱。例如,当所有浏览器完全支持非前缀版本时,许多开发者仅使用属性的 -webkit- 前缀版本。这意味着依赖该属性的设计在可以的情况下无法在非基于 webkit 的浏览器中运行。这成为一个严重的问题,以至于其他浏览器被迫实现 -webkit- 前缀别名以提高 Web 兼容性,如 兼容性生活标准 中所指定。

¥The use of such properties on production websites is not recommended — they have already created a huge web compatibility mess. For example, many developers only use the -webkit- prefixed version of a property when the non-prefixed version is fully supported across all browsers. This means a design relying on that property would not work in non-webkit-based browsers, when it could. This became a problem great enough that other browsers were pushed to implement -webkit- prefixed aliases to improve web compatibility, as specified in the Compatibility Living Standard.

浏览器在实现新的实验性功能时不再使用 CSS 前缀。相反,他们在可配置的实验标志后面测试新功能,或者仅在 Nightly 浏览器版本或类似版本上测试新功能。

¥Browsers no longer use CSS prefixes when implementing new experimental features. Rather, they test new features behind configurable experimental flags or only on Nightly browser versions or similar.

如果你需要在工作中使用前缀,请先编写带前缀的版本,然后编写无前缀的标准版本。这样,标准版本将在支持时自动覆盖前缀版本。例如:

¥If you are required to use prefixes in your work, write the prefixed versions first followed by the non-prefixed standard version. This way the standard version will automatically override the prefixed versions when supported. For example:

css
-webkit-text-stroke: 4px navy;
text-stroke: 4px navy;

注意:有关处理前缀属性的更多信息,请参阅 跨浏览器测试 模块中的 处理常见的 HTML 和 CSS 问题 - 处理 CSS 前缀

¥Note: For more information on dealing with prefixed properties, see Handling common HTML and CSS problems — Handling CSS prefixes from our Cross-browser testing module.

注意:有关浏览器前缀 CSS 属性的列表,请参阅 Mozilla CSS 扩展WebKit CSS 扩展

¥Note: See the Mozilla CSS Extensions and WebKit CSS Extensions for lists of browser-prefixed CSS properties.

z-index 与定位有何关系?

¥How does z-index relate to positioning?

z-index 属性指定元素的堆栈顺序。

¥The z-index property specifies the stack order of elements.

在屏幕上,具有较高 z 索引/堆栈顺序的元素始终呈现在具有较低 z 索引/堆栈顺序的元素前面。Z-index 仅适用于具有指定位置(position:absoluteposition:relativeposition:fixed)的元素。

¥An element with a higher z-index/stack order is always rendered in front of an element with a lower z-index/stack order on the screen. Z-index will only work on elements that have a specified position (position:absolute, position:relative, or position:fixed).

注意:有关更多信息,请参阅我们的 定位 学习文章,特别是 引入 z 索引 部分。

¥Note: For more information, see our Positioning learning article, and in particular the Introducing z-index section.