CSS 入门
在本文中,我们将使用一个简单的 HTML 文档并对其应用 CSS,并在此过程中学习一些有关该语言的实用知识。
¥In this article, we will take a simple HTML document and apply CSS to it, learning some practical things about the language along the way.
从一些 HTML 开始
¥Starting with some HTML
我们的起点是 HTML 文档。如果你想在自己的计算机上工作,可以复制下面的代码。将下面的代码保存为 index.html
到你计算机上的文件夹中。
¥Our starting point is an HTML document. You can copy the code from below if you want to work on your own computer. Save the code below as index.html
in a folder on your machine.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Getting started with CSS</title>
</head>
<body>
<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="https://example.com">link</a>.
</p>
<p>
This is the second paragraph. It contains an <em>emphasized</em> element.
</p>
<ul>
<li>Item <span>one</span></li>
<li>Item two</li>
<li>Item <em>three</em></li>
</ul>
</body>
</html>
注意:如果你在无法轻松创建文件的设备或环境上阅读本文,请不要担心 - 下面提供了实时代码编辑器,允许你在页面中编写示例代码。
¥Note: If you are reading this on a device or an environment where you can't easily create files, then don't worry — live code editors are provided below to allow you to write example code right here in the page.
将 CSS 添加到我们的文档中
¥Adding CSS to our document
我们需要做的第一件事就是告诉 HTML 文档我们希望它使用一些 CSS 规则。你通常会遇到将 CSS 应用到 HTML 文档的三种不同方法,但是现在,我们将介绍最常用和最有用的方法 — 从文档头部链接 CSS。
¥The very first thing we need to do is to tell the HTML document that we have some CSS rules we want it to use. There are three different ways to apply CSS to an HTML document that you'll commonly come across, however, for now, we will look at the most usual and useful way of doing so — linking CSS from the head of your document.
在与 HTML 文档相同的文件夹中创建一个文件,并将其另存为 styles.css
.txt。.css
扩展名表明这是一个 CSS 文件。
¥Create a file in the same folder as your HTML document and save it as styles.css
. The .css
extension shows that this is a CSS file.
要将 styles.css
链接到 index.html
,请在 HTML 文档的 <head>
内的某处添加以下行:
¥To link styles.css
to index.html
, add the following line somewhere inside the <head>
of the HTML document:
<link rel="stylesheet" href="styles.css" />
这个 <link>
元素告诉浏览器我们有一个样式表,使用 rel
属性,并且该样式表的位置作为 href
属性的值。你可以通过向 styles.css
添加规则来测试 CSS 是否正常工作。使用代码编辑器,将以下内容添加到 CSS 文件中:
¥This <link>
element tells the browser that we have a stylesheet, using the rel
attribute, and the location of that stylesheet as the value of the href
attribute. You can test that the CSS works by adding a rule to styles.css
. Using your code editor, add the following to your CSS file:
h1 {
color: red;
}
保存 HTML 和 CSS 文件并在 Web 浏览器中重新加载页面。文档顶部的一级标题现在应该是红色的。如果发生这种情况,恭喜你 — 你已成功将一些 CSS 应用到 HTML 文档中。如果没有发生这种情况,请仔细检查你输入的所有内容是否正确。
¥Save your HTML and CSS files and reload the page in a web browser. The level one heading at the top of the document should now be red. If that happens, congratulations — you have successfully applied some CSS to an HTML document. If that doesn't happen, carefully check that you've typed everything correctly.
你可以继续在本地使用 styles.css
,也可以使用下面的交互式编辑器继续本教程。交互式编辑器的作用就好像第一个面板中的 CSS 链接到 HTML 文档,就像我们上面的文档一样。
¥You can continue to work in styles.css
locally, or you can use our interactive editor below to continue with this tutorial. The interactive editor acts as if the CSS in the first panel is linked to the HTML document, just as we have with our document above.
HTML 元素样式
¥Styling HTML elements
通过将标题设为红色,我们已经证明了我们可以定位 HTML 元素并设置其样式。我们通过定位元素选择器来做到这一点 - 这是一个直接匹配 HTML 元素名称的选择器。要定位文档中的所有段落,你可以使用选择器 p
。要将所有段落变为绿色,你可以使用:
¥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 the same time by separating the selectors with a comma. If you want all paragraphs and all list items to be green, your rule would look like this:
p,
li {
color: green;
}
在下面的交互式编辑器(编辑代码框)或本地 CSS 文档中尝试一下。
¥Try this out in the interactive editor below (edit the code boxes) or in your local CSS document.
更改元素的默认行为
¥Changing the default behavior of elements
当我们查看标记良好的 HTML 文档时,即使是像我们的示例一样简单的文档,我们也可以看到浏览器如何通过添加一些默认样式来使 HTML 可读。标题又大又粗,我们的列表有项目符号。发生这种情况是因为浏览器有包含默认样式的内部样式表,它们默认应用于所有页面;如果没有它们,所有文本都会聚集在一起,我们将不得不从头开始设计所有内容。默认情况下,所有现代浏览器都以几乎相同的方式显示 HTML 内容。
¥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.
但是,你通常会想要浏览器所做的选择之外的其他内容。这可以通过选择要更改的 HTML 元素并使用 CSS 规则来更改其外观来完成。一个很好的例子是 <ul>
,一个无序列表。它有列表项目符号。如果你不想要这些项目符号,可以像这样删除它们:
¥However, you will often want something other than the choice the browser has made. This can be done by choosing the HTML element that you want to change and using a CSS rule to change the way it looks. A good example is <ul>
, an unordered list. It has list bullets. If you don't want those bullets, you can remove them like so:
li {
list-style-type: none;
}
现在尝试将其添加到你的 CSS 中。
¥Try adding this to your CSS now.
list-style-type
属性是一个很好的属性,可以在 MDN 上查看以了解支持哪些值。查看 list-style-type
的页面,你会在页面顶部找到一个交互式示例,可以在其中尝试一些不同的值,然后页面下方将详细介绍所有允许的值。
¥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.
查看该页面,你会发现除了删除列表项目符号之外,你还可以更改它们 - 尝试使用值 square
将它们更改为方形项目符号。
¥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
到目前为止,我们已经根据 HTML 元素名称设置了元素的样式。只要你希望文档中该类型的所有元素看起来都相同,这种方法就有效。要选择元素的子集而不更改其他元素,你可以向 HTML 元素添加一个类,并在 CSS 中定位该类。
¥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. To select a subset of the elements without changing the others, you can add a class to your HTML element and target that class in your CSS.
- 在 HTML 文档中,将 类属性 添加到第二个列表项。你的列表现在将如下所示:
html
<ul> <li>Item one</li> <li class="special">Item two</li> <li>Item <em>three</em></li> </ul>
- 在 CSS 中,你可以通过创建以句点开头的选择器来定位
special
类。将以下内容添加到你的 CSS 文件中:css.special { color: orange; font-weight: bold; }
- 保存并刷新看看结果是什么。
你可以将 special
类应用到页面上你希望与此列表项具有相同外观的任何元素。例如,你可能希望段落中的 <span>
也为橙色且粗体。尝试向其中添加 class
或 special
,然后重新加载页面,看看会发生什么。
¥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.
有时你会看到带有选择器的规则,其中列出了 HTML 元素选择器以及类:
¥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;
}
此语法的意思是“定位任何具有特殊类别的 li
元素”。如果你要这样做,那么你将无法再通过向 <span>
或其他元素添加类来将该类应用于该元素;你必须将该元素添加到选择器列表中:
¥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 adding the class to it; you would have to add that element to the list of selectors:
li.special,
span.special {
color: orange;
font-weight: bold;
}
正如你可以想象的那样,某些类可能会应用于许多元素,并且你不希望每次有新内容需要采用该样式时都必须继续编辑 CSS。因此,有时最好绕过元素并引用类,除非你知道想要单独为一个元素创建一些特殊规则,并且可能想要确保它们不会应用于其他事物。
¥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 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
有时,你会希望某些内容根据其在文档中的位置而看起来有所不同。有许多选择器可以在这里为你提供帮助,但现在我们只看其中几个。在我们的文档中,有两个 <em>
元素 - 一个在段落内,另一个在列表项内。要仅选择嵌套在 <li>
元素内的 <em>
,你可以使用称为后代组合器的选择器,它采用两个其他选择器之间的空格形式。
¥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, there 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, you can use a selector called the descendant combinator, which takes the form of a space between two other selectors.
将以下规则添加到你的样式表中:
¥Add the following rule to your stylesheet:
li em {
color: rebeccapurple;
}
该选择器将选择 <li>
内部(其后代)的任何 <em>
元素。因此,在你的示例文档中,你应该发现第三个列表项中的 <em>
现在是紫色的,但段落内的 <em>
没有变化。
¥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.
你可能想要尝试的其他方法是,当段落直接位于 HTML 中同一层次结构级别的标题之后时,对段落进行样式设置。为此,请在选择器之间放置一个 +
(下一个兄弟组合器)。
¥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 next-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 because the span in the first paragraph will be red, but the one in the first list item will not change color.
注意:正如你所看到的,CSS 为我们提供了多种定位元素的方法,但到目前为止我们只触及了皮毛!我们将在课程后面的 选择器 文章中仔细研究所有这些选择器以及更多内容。
¥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
我们将在本教程中讨论的最后一种样式类型是根据事物的状态对其进行样式设置的能力。一个简单的例子就是设置链接样式。当我们设置链接样式时,我们需要定位 <a>
(锚点)元素。它具有不同的状态,具体取决于它是未访问、已访问、悬停在其上、通过键盘获得焦点还是正在被单击(激活)过程中。你可以使用 CSS 来定位这些不同的状态 - 下面的 CSS 将未访问的链接设置为粉红色,将访问的链接设置为绿色。
¥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 by removing the underline, which is achieved by 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. We have added the rules above to it, and now realize 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?
我们已经删除了悬停链接上的下划线。你可以从链接的所有状态中删除下划线。然而,值得记住的是,在真实的网站中,你需要确保访问者知道链接就是链接。保留下划线可能是人们意识到可以单击段落内的某些文本的重要线索 - 这是他们习惯的行为。与 CSS 中的所有内容一样,你的更改可能会使文档变得更难访问 - 我们将致力于在适当的位置高亮潜在的陷阱。
¥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.
注意:你会经常在这些课程和 MDN 中看到对 accessibility 的提及。当我们谈论可访问性时,我们指的是每个人都可以理解和使用我们的网页的要求。
¥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 screen reader, 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.
纯 HTML 文档通常可供所有人访问 - 当你开始设计该文档的样式时,不要使其变得难以访问,这一点很重要。
¥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;
}
这将为任何具有 special
类的元素设置样式,special
位于 <p>
内,<p>
紧随 <h1>
之后,而 <h1>
位于 <body>
内。唷!
¥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!
在我们提供的原始 HTML 中,唯一的样式元素是 <span class="special">
。
¥In the original HTML we provided, the only element styled is <span class="special">
.
如果现在这看起来很复杂,请不要担心 - 随着你编写更多 CSS,你很快就会开始掌握它的窍门。
¥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.
概括
¥Summary
在本文中,我们了解了使用 CSS 设计文档样式的多种方法。我们将在学习其余课程的过程中加深对这些知识的了解。不过,你现在已经足够了解如何设置文本样式、根据定位文档中元素的不同方式应用 CSS,以及在 MDN 文档中查找属性和值。
¥In this article, 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.
在下一课中,我们将讨论 CSS 是如何构造的。
¥In the next lesson, we'll be taking a look at how CSS is structured.