调试 CSS

有时,在编写 CSS 时,你会遇到 CSS 似乎没有达到你预期的效果的问题。也许你认为某个选择器应该与某个元素匹配,但没有任何反应,或者框的大小与你预期的不同。本文将指导你如何调试 CSS 问题,并向你展示所有现代浏览器中包含的 DevTools 如何帮助你找出正在发生的情况。

¥Sometimes when writing CSS you will encounter an issue where your CSS doesn't seem to be doing what you expect. Perhaps you believe that a certain selector should match an element, but nothing happens, or a box is a different size than you expected. This article will give you guidance on how to go about debugging a CSS problem, and show you how the DevTools included in all modern browsers can help you to find out what is going on.

先决条件: 基本软件已安装处理文件 的基础知识、HTML 基础知识(学习 HTML 简介)以及 CSS 工作原理的想法(学习 CSS 第一步)。
目标: 了解浏览器 DevTools 的基础知识,以及如何对 CSS 进行简单的检查和编辑。

如何访问浏览器开发工具

¥How to access browser DevTools

文章 什么是浏览器开发工具 是最新指南,解释如何在各种浏览器和平台中访问这些工具。虽然你可能选择主要在特定浏览器中进行开发,因此会最熟悉该浏览器中包含的工具,但了解如何在其他浏览器中访问它们是值得的。如果你在多个浏览器之间看到不同的渲染,这将有所帮助。

¥The article What are browser developer tools is an up-to-date guide explaining how to access the tools in various browsers and platforms. While you may choose to mostly develop in a particular browser, and therefore will become most familiar with the tools included in that browser, it is worth knowing how to access them in other browsers. This will help if you are seeing different rendering between multiple browsers.

你还会发现浏览器在创建开发工具时选择关注不同的字段。例如,在 Firefox 中,有一些出色的工具可用于可视化地使用 CSS 布局,允许你检查和编辑 网格布局弹性盒形状。然而,所有不同的浏览器都有相似的基本工具,例如,用于检查应用于页面上元素的属性和值,并从编辑器对它们进行更改。

¥You will also find that browsers have chosen to focus on different areas when creating their DevTools. For example, in Firefox there are some excellent tools for working visually with CSS Layout, allowing you to inspect and edit Grid Layouts, Flexbox, and Shapes. However, all of the different browsers have similar fundamental tools, e.g., for inspecting the properties and values applied to elements on your page, and making changes to them from the editor.

在本课中,我们将了解 Firefox DevTools 的一些用于处理 CSS 的有用功能。为此,我将使用 示例文件。如果你想继续操作,请在新选项卡中加载此内容,然后按照上面链接的文章中所述打开开发工具。

¥In this lesson we will look at some useful features of the Firefox DevTools for working with CSS. In order to do so I'll be using an example file. Load this up in a new tab if you want to follow along, and open up your DevTools as described in the article linked above.

DOM 与查看源代码

¥The DOM versus view source

DevTools 新手可能会遇到的一个问题是,当你对网页进行 查看源码 操作或查看放置在服务器上的 HTML 文件时所看到的内容与在 DevTools 的 HTML 窗格 中看到的内容之间存在差异。虽然它看起来与你通过“查看源代码”看到的大致相似,但还是存在一些差异。

¥Something that can trip up newcomers to DevTools is the difference between what you see when you view the source of a webpage, or look at the HTML file you put on the server, and what you can see in the HTML Pane of the DevTools. While it looks roughly similar to what you can see via View Source there are some differences.

在渲染的 DOM 中,浏览器可能已经标准化了 HTML,例如通过为你纠正一些写得不好的 HTML。如果你错误地关闭了一个元素,例如打开 <h2> 但用 </h3> 关闭,浏览器将弄清楚你想要做什么,并且 DOM 中的 HTML 将正确地用 </h2> 关闭打开的 <h2>。DOM 还将显示 JavaScript 所做的任何更改。

¥In the rendered DOM the browser may have normalized the HTML, for example by correcting some badly-written HTML for you. If you incorrectly closed an element, for instance by opening an <h2> but closing with an </h3>, the browser will figure out what you were meaning to do and the HTML in the DOM will correctly close the open <h2> with an </h2>. The DOM will also show any changes made by JavaScript.

相比之下,查看源代码是存储在服务器上的 HTML 源代码。DevTools 中的 HTML 树 准确显示浏览器在任何给定时间呈现的内容,因此它可以让你深入了解到底发生了什么。

¥View Source, in comparison, is the HTML source code as stored on the server. The HTML tree in your DevTools shows exactly what the browser is rendering at any given time, so it gives you an insight into what is really going on.

检查应用的 CSS

¥Inspecting the applied CSS

选择页面上的一个元素,方法是右键/按住 Ctrl 键单击该元素并选择“检查”,或者从 DevTools 显示左侧的 HTML 树中选择它。尝试选择类为 box1 的元素;这是页面上的第一个元素,周围绘制有边框。

¥Select an element on your page, either by right/ctrl-clicking on it and selecting Inspect, or selecting it from the HTML tree on the left of the DevTools display. Try selecting the element with the class of box1; this is the first element on the page with a bordered box drawn around it.

The example page for this tutorial with DevTools open.

如果你查看 HTML 右侧的 规则视图,你应该能够看到应用于该元素的 CSS 属性和值。你将看到直接应用于类 box1 的规则,以及盒子从其祖级(在本例中是从 <body>)继承的 CSS。如果你发现应用了一些意想不到的 CSS,这会很有用。也许它是从父元素继承的,你需要添加一条规则以在此元素的上下文中覆盖它。

¥If you look at the Rules view to the right of your HTML, you should be able to see the CSS properties and values applied to that element. You will see the rules directly applied to class box1 and also the CSS that is being inherited by the box from its ancestors, in this case from <body>. This is useful if you are seeing some CSS being applied that you didn't expect. Perhaps it is being inherited from a parent element and you need to add a rule to overwrite it in the context of this element.

扩展速记属性的能力也很有用。在我们的示例中,使用了 margin 简写。

¥Also useful is the ability to expand out shorthand properties. In our example the margin shorthand is used.

单击小箭头展开视图,显示不同的普通属性及其值。

¥Click on the little arrow to expand the view, showing the different longhand properties and their values.

当该面板处于活动状态时,你可以打开和关闭“规则”视图中的值 - 如果将鼠标悬停在其上,则会出现复选框。取消选中规则的复选框,例如 border-radius,CSS 将停止应用。

¥You can toggle values in the Rules view on and off when that panel is active — if you hold your mouse over it, checkboxes will appear. Uncheck a rule's checkbox, for example border-radius, and the CSS will stop applying.

你可以使用它进行 A/B 比较,确定应用规则后某些内容是否看起来更好,还可以帮助调试它 - 例如,如果布局出错,而你正在尝试找出哪个属性是错误的 导致问题。

¥You can use this to do an A/B comparison, deciding if something looks better with a rule applied or not, and also to help debug it — for example, if a layout is going wrong and you are trying to work out which property is causing the problem.

以下视频提供了一些有关使用 Firefox DevTools 调试 CSS 的有用提示:

¥The following video provides some useful tips on debugging CSS using the Firefox DevTools:

编辑值

¥Editing values

除了打开和关闭属性之外,你还可以编辑它们的值。也许你想看看另一种颜色是否看起来更好,或者希望调整某些东西的大小?DevTools 可以为你节省大量编辑样式表和重新加载页面的时间。

¥In addition to turning properties on and off, you can edit their values. Perhaps you want to see if another color looks better, or wish to tweak the size of something? DevTools can save you a lot of time editing a stylesheet and reloading the page.

选择 box1 后,单击显示应用于边框的颜色的样本(小彩色圆圈)。将打开一个颜色选择器,你可以尝试一些不同的颜色;这些将在页面上实时更新。以类似的方式,你可以更改边框的宽度或样式。

¥With box1 selected, click on the swatch (the small colored circle) that shows the color applied to the border. A color picker will open up and you can try out some different colors; these will update in real time on the page. In a similar fashion, you could change the width or style of the border.

DevTools Styles Panel with a color picker open.

添加新属性

¥Adding a new property

你可以使用 DevTools 添加属性。也许你已经意识到你不希望你的框继承 <body> 元素的字体大小,并希望设置自己的特定大小?在将其添加到 CSS 文件之前,你可以在 DevTools 中尝试一下。

¥You can add properties using the DevTools. Perhaps you have realized that you don't want your box to inherit the <body> element's font size, and want to set its own specific size? You can try this out in DevTools before adding it to your CSS file.

你可以单击规则中的右大括号开始在其中输入新声明,此时你可以开始输入新属性,DevTools 将显示匹配属性的自动补齐列表。选择 font-size 后,输入你想要尝试的值。你还可以单击 + 按钮使用相同的选择器添加其他规则,然后在其中添加新规则。

¥You can click the closing curly brace in the rule to start entering a new declaration into it, at which point you can start typing the new property and DevTools will show you an autocomplete list of matching properties. After selecting font-size, enter the value you want to try. You can also click the + button to add an additional rule with the same selector, and add your new rules there.

The DevTools Panel, adding a new property to the rules, with the autocomplete for font- open

注意:规则视图中还有其他有用的功能,例如具有无效值的声明会被划掉。你可以在 检查和编辑 CSS 上了解更多信息。

¥Note: There are other useful features in the Rules view too, for example declarations with invalid values are crossed out. You can find out more at Examine and edit CSS.

理解盒子模型

¥Understanding the box model

在前面的课程中,我们讨论了 盒子模型,以及我们有一个替代盒模型的事实,该模型可以根据你给定的大小以及填充和边框来更改元素大小的计算方式。DevTools 确实可以帮助你了解如何计算元素的大小。

¥In previous lessons we have discussed the Box Model, and the fact that we have an alternate box model that changes how the size of elements are calculated based on the size you give them, plus the padding and borders. DevTools can really help you to understand how the size of an element is being calculated.

布局视图 向你显示所选元素上的盒模型图,以及更改元素布局方式的属性和值的描述。这包括你可能未在元素上明确使用但确实设置了初始值的属性的描述。

¥The Layout view shows you a diagram of the box model on the selected element, along with a description of the properties and values that change how the element is laid out. This includes a description of properties that you may not have explicitly used on the element, but which do have initial values set.

在此面板中,详细属性之一是 box-sizing 属性,它控制元素使用的盒模型。

¥In this panel, one of the detailed properties is the box-sizing property, which controls what box model the element uses.

比较 box1box2 类的两个盒子。它们都应用了相同的宽度 (400px),但 box1 视觉上更宽。你可以在布局面板中看到它正在使用 content-box。该值采用你为元素指定的大小,然后添加填充和边框宽度。

¥Compare the two boxes with classes box1 and box2. They both have the same width applied (400px), however box1 is visually wider. You can see in the layout panel that it is using content-box. This is the value that takes the size you give the element and then adds on the padding and border width.

类为 box2 的元素正在使用 border-box,因此这里从你为元素指定的大小中减去填充和边框。这意味着该框在页面上占用的空间正是你指定的大小 - 在我们的例子中为 width: 400px

¥The element with a class of box2 is using border-box, so here the padding and border is subtracted from the size that you have given the element. This means that the space taken up on the page by the box is the exact size that you specified — in our case width: 400px.

The Layout section of the DevTools

注意:在 检查和检验盒子模型 中了解更多信息。

¥Note: Find out more in Examining and Inspecting the Box Model.

解决特异性问题

¥Solving specificity issues

有时在开发过程中,特别是当你需要在现有站点上编辑 CSS 时,你会发现自己很难应用一些 CSS。无论你做什么,该元素似乎都不采用 CSS。这里通常发生的情况是,一个更具体的选择器会覆盖你的更改,而这里 DevTools 将真正帮助你。

¥Sometimes during development, but in particular when you need to edit the CSS on an existing site, you will find yourself having a hard time getting some CSS to apply. No matter what you do, the element just doesn't seem to take the CSS. What is generally happening here is that a more specific selector is overriding your changes, and here DevTools will really help you out.

在我们的示例文件中,有两个单词被封装在 <em> 元素中。一个显示为橙色,另一个显示为亮粉色。在 CSS 中我们应用了:

¥In our example file there are two words that have been wrapped in an <em> element. One is displaying as orange and the other hotpink. In the CSS we have applied:

css
em {
  color: hotpink;
  font-weight: bold;
}

然而,样式表中的上方是带有 .special 选择器的规则:

¥Above that in the stylesheet however is a rule with a .special selector:

css
.special {
  color: orange;
}

你会记得我们在 级联和继承 课程中讨论了特异性,类选择器比元素选择器更具体,因此这是适用的值。DevTools 可以帮助你找到此类问题,特别是当信息隐藏在巨大的样式表中的某个位置时。

¥As you will recall from the lesson on cascade and inheritance where we discussed specificity, class selectors are more specific than element selectors, and so this is the value that applies. DevTools can help you find such issues, especially if the information is buried somewhere in a huge stylesheet.

使用 .special 类检查 <em>,DevTools 将显示橙色是适用的颜色,并且应用于 <em>color 属性已被划掉。你现在可以看到类选择器正在覆盖元素选择器。

¥Inspect the <em> with the class of .special and DevTools will show you that orange is the color that applies, and also that the color property applied to the <em> is crossed out. You can now see that the class selector is overriding the element selector.

Selecting an em and looking at DevTools to see what is over-riding the color.

了解有关 Firefox 开发工具的更多信息

¥Find out more about the Firefox DevTools

MDN 上有很多有关 Firefox DevTools 的信息。看一下主要的 开发工具部分,有关我们在本课中简要介绍的内容的更多详细信息,请参阅 操作指南

¥There is a lot of information about the Firefox DevTools here on MDN. Take a look at the main DevTools section, and for more detail on the things we have briefly covered in this lesson see The How To Guides.

CSS 中的调试问题

¥Debugging problems in CSS

DevTools 在解决 CSS 问题时可以提供很大的帮助,因此当你发现 CSS 的行为不符合你的预期时,你应该如何解决它?以下步骤应该有所帮助。

¥DevTools can be a great help when solving CSS problems, so when you find yourself in a situation where CSS isn't behaving as you expect, how should you go about solving it? The following steps should help.

从问题中退一步

¥Take a step back from the problem

任何编码问题都可能令人沮丧,尤其是 CSS 问题,因为你通常不会收到错误消息来在线搜索以帮助找到解决方案。如果你感到沮丧,暂时远离这个问题 - 出去散步、喝一杯、和同事聊天,或者暂时做点其他事情。有时,当你停止思考问题时,解决方案就会神奇地出现,即使没有,当你感觉精神焕发时,解决问题也会容易得多。

¥Any coding problem can be frustrating, especially CSS problems because you often don't get an error message to search for online to help with finding a solution. If you are becoming frustrated, take a step away from the issue for a while — go for a walk, grab a drink, chat to a co-worker, or work on some other thing for a while. Sometimes the solution magically appears when you stop thinking about the problem, and even if not, working on it when feeling refreshed will be much easier.

你有有效的 HTML 和 CSS 吗?

¥Do you have valid HTML and CSS?

浏览器希望你的 CSS 和 HTML 能够正确编写,但浏览器也非常宽容,即使你的标记或样式表中有错误,也会尽力显示你的网页。如果你的代码中有错误,浏览器需要猜测你的意思,并且它可能会做出与你的想法不同的决定。此外,两种不同的浏览器可能会以两种不同的方式处理该问题。因此,好的第一步是通过验证器运行 HTML 和 CSS,以发现并修复任何错误。

¥Browsers expect your CSS and HTML to be correctly written, however browsers are also very forgiving and will try their best to display your webpages even if you have errors in the markup or stylesheet. If you have mistakes in your code the browser needs to make a guess at what you meant, and it might make a different decision to what you had in mind. In addition, two different browsers might cope with the problem in two different ways. A good first step, therefore, is to run your HTML and CSS through a validator, to pick up and fix any errors.

你正在测试的浏览器是否支持该属性和值?

¥Are the property and value supported by the browser you are testing in?

浏览器会忽略它们不理解的 CSS。如果你正在测试的浏览器不支持你正在使用的属性或值,则不会出现任何问题,但不会应用 CSS。DevTools 通常会以某种方式高亮不支持的属性和值。在下面的屏幕截图中,浏览器不支持 grid-template-columns 的子网格值。

¥Browsers ignore CSS they don't understand. If the property or value you are using is not supported by the browser you are testing in then nothing will break, but that CSS won't be applied. DevTools will generally highlight unsupported properties and values in some way. In the screenshot below the browser does not support the subgrid value of grid-template-columns.

Image of browser DevTools with the grid-template-columns: subgrid crossed out as the subgrid value is not supported.

你还可以查看 MDN 上每个属性页面底部的浏览器兼容性表。这些向你显示浏览器对该属性的支持,如果支持该属性的某些用法而不是其他属性,则通常会崩溃。请参阅 shape-outside 属性的兼容性表

¥You can also take a look at the Browser compatibility tables at the bottom of each property page on MDN. These show you browser support for that property, often broken down if there is support for some usage of the property and not others. See the compatibility table for the shape-outside property.

是否有其他内容覆盖了你的 CSS?

¥Is something else overriding your CSS?

这就是你所学到的有关特异性的信息将发挥很大作用的地方。如果你有一些更具体的事情压倒了你想做的事情,你可能会陷入一个非常令人沮丧的游戏,试图弄清楚什么。然而,如上所述,DevTools 将向你显示正在应用的 CSS,并且你可以弄清楚如何使新选择器足够具体以覆盖它。

¥This is where the information you have learned about specificity will come into much use. If you have something more specific overriding what you are trying to do, you can enter into a very frustrating game of trying to work out what. However, as described above, DevTools will show you what CSS is applying and you can work out how to make the new selector specific enough to override it.

减少问题的测试用例

¥Make a reduced test case of the problem

如果上述步骤未能解决问题,那么你将需要进行更多调查。此时最好的做法是创建称为简化测试用例的东西。能够 "减少一个问题" 是一项非常有用的技能。它将帮助你发现自己和同事代码中的问题,并且还使你能够更有效地报告错误并寻求帮助。

¥If the issue isn't solved by the steps above, then you will need to do some more investigating. The best thing to do at this point is to create something known as a reduced test case. Being able to "reduce an issue" is a really useful skill. It will help you find problems in your own code and that of your colleagues, and will also enable you to report bugs and ask for help more effectively.

简化测试用例是一个代码示例,它以尽可能简单的方式演示问题,删除了不相关的周围内容和样式。这通常意味着将有问题的代码从布局中取出来制作一个仅显示该代码或功能的小示例。

¥A reduced test case is a code example that demonstrates the problem in the simplest possible way, with unrelated surrounding content and styling removed. This will often mean taking the problematic code out of your layout to make a small example which only shows that code or feature.

要创建简化的测试用例:

¥To create a reduced test case:

  1. 如果你的标记是动态生成的(例如通过 CMS),请制作显示问题的输出的静态版本。像 CodePen 这样的代码共享网站对于托管简化的测试用例非常有用,因为这样可以在线访问它们,并且你可以轻松地与同事共享它们。你可以首先在页面上查看源代码并将 HTML 复制到 CodePen 中,然后获取任何相关的 CSS 和 JavaScript 并将其包含在内。之后,你可以检查问题是否仍然明显。
  2. 如果删除 JavaScript 不能解决问题,则不要包含 JavaScript。如果删除 JavaScript 确实可以解决问题,那么请删除尽可能多的 JavaScript,保留导致问题的原因。
  3. 删除任何与此问题无关的 HTML。删除布局的组件甚至主要元素。再次,尝试减少仍然显示问题的最少代码量。
  4. 删除任何不会影响该问题的 CSS。

在执行此操作的过程中,你可能会发现导致问题的原因,或者至少能够通过删除特定的内容来打开和关闭它。当你发现一些东西时,值得在代码中添加一些注释。如果你需要寻求帮助,他们会向帮助你的人展示你已经尝试过的方法。这很可能为你提供足够的信息,以便能够搜索可能的问题和解决方法。

¥In the process of doing this, you may discover what is causing the problem, or at least be able to turn it on and off by removing something specific. It is worth adding some comments to your code as you discover things. If you need to ask for help, they will show the person helping you what you have already tried. This may well give you enough information to be able to search for likely problems and workarounds.

如果你仍在努力解决问题,那么减少测试用例可以让你通过在论坛上发帖或向同事展示来寻求帮助。如果你能够在寻求帮助之前证明自己已经完成了减少问题并准确确定问题发生位置的工作,那么你获得帮助的可能性就会大得多。经验丰富的开发者可能能够快速发现问题并为你指明正确的方向,即使不能,你减少的测试用例也将使他们能够快速查看并希望能够提供至少一些帮助。

¥If you are still struggling to fix the problem then having a reduced test case gives you something to ask for help with, by posting to a forum, or showing to a co-worker. You are much more likely to get help if you can show that you have done the work of reducing the problem and identifying exactly where it happens, before asking for help. A more experienced developer might be able to quickly spot the problem and point you in the right direction, and even if not, your reduced test case will enable them to have a quick look and hopefully be able to offer at least some help.

如果你的问题实际上是浏览器中的错误,则还可以使用简化的测试用例向相关浏览器供应商提交错误报告(例如在 Mozilla 的 bugzilla 网站 上)。

¥In the instance that your problem is actually a bug in a browser, then a reduced test case can also be used to file a bug report with the relevant browser vendor (e.g. on Mozilla's bugzilla site).

随着你对 CSS 的了解越来越丰富,你会发现解决问题的速度越来越快。然而,即使是我们中最有经验的人有时也会发现自己想知道到底发生了什么。采取有条不紊的方法,减少测试用例并向其他人解释问题通常会导致找到解决方案。

¥As you become more experienced with CSS, you will find that you get faster at figuring out issues. However, even the most experienced of us sometimes find ourselves wondering what on earth is going on. Taking a methodical approach, making a reduced test case, and explaining the issue to someone else will usually result in a fix being found.

概括

¥Summary

因此,我们有它:调试 CSS 的简介,当你在职业生涯后期开始调试 CSS 和其他类型的代码时,这应该为你提供一些有用的技能。

¥So there we have it: an introduction to debugging CSS, which should give you some useful skills to count on when you start to debug CSS and other types of code later on in your career.

在本模块的最后一篇文章中,我们将了解如何 组织你的 CSS

¥In the last article of this module, we'll take a look at how to organize your CSS.