CSS 值和单位

CSS 规则包含 declarationsdeclarations 又由属性和值组成。CSS 中使用的每个属性都有一个值类型,用于描述允许其具有的值类型。在本课中,我们将了解一些最常用的值类型、它们是什么以及它们如何工作。

¥CSS rules contain declarations, which in turn are composed of properties and values. Each property used in CSS has a value type that describes what kind of values it is allowed to have. In this lesson, we will take a look at some of the most frequently used value types, what they are, and how they work.

注意:每个 CSS 属性页 都有一个语法部分,列出了可与该属性一起使用的值类型。

¥Note: Each CSS property page has a syntax section that lists the value types you can use with that property.

先决条件: 基本软件已安装处理文件 的基础知识、HTML 基础知识(研究 HTML 简介)以及 CSS 工作原理的想法(研究 CSS 第一步)。
目标: 了解 CSS 属性中使用的不同类型的值和单位。

什么是 CSS 值?

¥What is a CSS value?

在 CSS 规范和 MDN 的属性页面中,你将能够发现值类型,因为它们会被尖括号包围,例如 <color><length>。当你看到值类型 <color> 对于特定属性有效时,这意味着你可以使用任何有效颜色作为该属性的值,如 <color> 参考页上所列。

¥In CSS specifications and on the property pages here on MDN you will be able to spot value types as they will be surrounded by angle brackets, such as <color> or <length>. When you see the value type <color> as valid for a particular property, that means you can use any valid color as a value for that property, as listed on the <color> reference page.

注意:你将看到 CSS 值类型被称为数据类型。这些术语基本上是可以互换的 - 当你在 CSS 中看到一些被称为数据类型的东西时,它实际上只是一种表达值类型的奇特方式。术语“值”是指你选择使用的值类型支持的任何特定表达式。

¥Note: You'll see CSS value types referred to as data types. The terms are basically interchangeable — when you see something in CSS referred to as a data type, it is really just a fancy way of saying value type. The term value refers to any particular expression supported by a value type that you choose to use.

注意:CSS 值类型往往括在尖括号(<>)中,以将其与 CSS 属性区分开来。例如,有 color 属性和 <color> 数据类型。不要将其与 HTML 元素混淆,因为它们也使用尖括号,但要记住这一点,上下文应该清楚。

¥Note: CSS value types tend to be enclosed in angle brackets (<, >) to differentiate them from CSS properties. For example there is a color property and a <color> data type. This is not to be confused with HTML elements, as they also use angle brackets, but this is something to keep in mind that the context should make clear.

在下面的示例中,我们使用关键字设置标题的颜色,并使用 rgb() 函数设置背景:

¥In the following example, we have set the color of our heading using a keyword, and the background using the rgb() function:

css
h1 {
  color: black;
  background-color: rgb(197 93 161);
}

CSS 中的值类型是一种定义允许值集合的方法。这意味着,如果你认为 <color> 有效,你无需想知道可以使用哪种不同类型的颜色值 - 关键字、十六进制值、rgb() 函数等。你可以使用任何可用的 <color> 值,假设它们受支持 通过你的浏览器。MDN 上每个值的页面将为你提供有关浏览器支持的信息。例如,如果你查看 <color> 的页面,你将看到浏览器兼容性部分列出了不同类型的颜色值及其支持。

¥A value type in CSS is a way to define a collection of allowable values. This means that if you see <color> as valid you don't need to wonder which of the different types of color value can be used — keywords, hex values, rgb() functions, etc. You can use any available <color> values, assuming they are supported by your browser. The page on MDN for each value will give you information about browser support. For example, if you look at the page for <color> you will see that the browser compatibility section lists different types of color values and support for them.

让我们看一下你可能经常遇到的一些值和单位类型,并举例说明,以便你可以尝试不同的可能值。

¥Let's have a look at some of the types of values and units you may frequently encounter, with examples so that you can try out different possible values.

数字、长度和百分比

¥Numbers, lengths, and percentages

你可能会发现自己在 CSS 中使用了多种数值类型。以下均被归类为数字:

¥There are various numeric value types that you might find yourself using in CSS. The following are all classed as numeric:

数据类型 描述
<integer> <integer> 是整数,例如 XSPACE1024-55
<number> <number> 代表十进制数 — 它可能有也可能没有带小数部分的小数点。例如, XSPACE0.255XSPACE128-1.2
<dimension> <dimension> 是附有一个单元的 <number>。例如, XSPACE45degXSPACE5sXSPACE10px<dimension> 是一个总类别,包括 <length><angle><time><resolution> 类型。
<percentage> <percentage> 代表某个其他值的一小部分。例如, XSPACE50%。百分比值始终相对于另一个数量。例如,元素的长度是相对于其父元素的长度的。

长度

¥Lengths

你最常遇到的数字类型是 <length>。例如,10px(像素)或 30em。CSS 中使用两种类型的长度 - 相对长度和绝对长度。为了了解事情将会变得有多大,了解其中的差异非常重要。

¥The numeric type you will come across most frequently is <length>. For example, 10px (pixels) or 30em. There are two types of lengths used in CSS — relative and absolute. It's important to know the difference in order to understand how big things will become.

绝对长度单位

¥Absolute length units

以下都是绝对长度单位 - 它们与其他任何单位无关,并且通常被认为始终具有相同的大小。

¥The following are all absolute length units — they are not relative to anything else, and are generally considered to always be the same size.

单元 名称 相当于
cm 厘米 1 厘米 = 37.8 像素 = 25.2/64 英寸
mm 毫米 1mm = 1cm 的 1/10
Q 四分之一毫米 1Q = 1cm 的 1/40
in 英寸 1 英寸 = 2.54 厘米 = 96 像素
pc 毕卡斯 1 件 = 1 英寸的 1/6
pt 积分 1 点 = 1 英寸的 1/72
px 像素 1 像素 = 1 英寸的 1/96

大多数这些单位在用于打印时比用于屏幕输出更有用。例如,我们通常不会在屏幕上使用 cm(厘米)。你常用的唯一值是 px(像素)。

¥Most of these units are more useful when used for print, rather than screen output. For example, we don't typically use cm (centimeters) on screen. The only value that you will commonly use is px (pixels).

相对长度单位

¥Relative length units

相对长度单位是相对于其他东西的。例如:

¥Relative length units are relative to something else. For example:

  • emrem 分别相对于父元素和根元素的字体大小。
  • vhvw 分别相对于视口的高度和宽度。

使用相对单位的好处是,通过一些仔细的规划,你可以使文本或其他元素的大小相对于页面上的其他所有内容进行缩放。有关可用相对单位的完整列表,请参阅 <length> 类型的参考页。

¥The benefit of using relative units is that with some careful planning you can make it so the size of text or other elements scales relative to everything else on the page. For a complete list of the relative units available, see the reference page for the <length> type.

在本节中,我们将探讨一些最常见的相对单位。

¥In this section we'll explore some of the most common relative units.

探索一个例子

¥Exploring an example

在下面的示例中,你可以看到一些相对和绝对长度单位的行为方式。第一个框的像素为 width。作为绝对单位,无论发生什么变化,该宽度都将保持不变。

¥In the example below, you can see how some relative and absolute length units behave. The first box has a width set in pixels. As an absolute unit, this width will remain the same no matter what else changes.

第二个框的宽度设置为 vw(视口宽度)单位。该值与视口宽度相关,因此 10vw 是视口宽度的 10%。如果更改浏览器窗口的宽度,框的大小也会发生变化。但是,此示例使用 <iframe> 嵌入到页面中,因此这不起作用。要查看此操作的实际效果,你必须 在自己的浏览器选项卡中打开示例后尝试该示例

¥The second box has a width set in vw (viewport width) units. This value is relative to the viewport width, and so 10vw is 10 percent of the width of the viewport. If you change the width of your browser window, the size of the box should change. However this example is embedded into the page using an <iframe>, so this won't work. To see this in action you'll have to try the example after opening it in its own browser tab.

第三个盒子使用 em 单位。这些与字体大小有关。我在包含 <div> 的内容上设置了 1em 的字体大小,该 <div> 的类为 .wrapper。将此值更改为 1.5em,你将看到所有元素的字体大小都会增加,但只有最后一项会变宽,因为它的宽度是相对于该字体大小的。

¥The third box uses em units. These are relative to the font size. I've set a font size of 1em on the containing <div>, which has a class of .wrapper. Change this value to 1.5em and you will see that the font size of all the elements increases, but only the last item will get wider, as its width is relative to that font size.

按照上述说明操作后,尝试以其他方式使用这些值,看看会得到什么。

¥After following the instructions above, try playing with the values in other ways, to see what you get.

ems 和 rems

¥ems and rems

emrem 是你在调整从框到文本的大小时最常遇到的两个相对长度。了解它们的工作原理以及它们之间的差异是值得的,尤其是当你开始学习 设置文本样式CSS 布局 等更复杂的主题时。下面的示例提供了演示。

¥em and rem are the two relative lengths you are likely to encounter most frequently when sizing anything from boxes to text. It's worth understanding how these work, and the differences between them, especially when you start getting on to more complex subjects like styling text or CSS layout. The below example provides a demonstration.

下面所示的 HTML 是一组嵌套列表 - 我们总共有两个列表,并且两个示例都具有相同的 HTML。唯一的区别是第一个有 ems 类,第二个有 rems 类。

¥The HTML illustrated below is a set of nested lists — we have two lists in total and both examples have the same HTML. The only difference is that the first has a class of ems and the second a class of rems.

首先,我们将 <html> 元素的字体大小设置为 16px。

¥To start with, we set 16px as the font size on the <html> element.

回顾一下,em 单位在排版中意味着 "我的父元素的字体大小"。<ul> 内的 <li> 元素(classems)从其父元素获取尺寸。因此,每个连续的嵌套级别都会逐渐变大,因为每个级别的字体大小都设置为 1.3em — 其父级字体大小的 1.3 倍。

¥To recap, the em unit means "my parent element's font-size" in the case of typography. The <li> elements inside the <ul> with a class of ems take their sizing from their parent. So each successive level of nesting gets progressively larger, as each has its font size set to 1.3em — 1.3 times its parent's font size.

回顾一下,rem 单位表示 "根元素的字体大小"(rem 代表 "根 em")。<ul> 内的 <li> 元素(classrems)从根元素 (<html>) 获取其大小。这意味着每个连续的嵌套级别不会不断变大。

¥To recap, the rem unit means "The root element's font-size" (rem stands for "root em"). The <li> elements inside the <ul> with a class of rems take their sizing from the root element (<html>). This means that each successive level of nesting does not keep getting larger.

但是,如果你在 CSS 中更改 <html> 元素的 font-size,你将看到其他所有内容都与其相关 - remem 大小的文本。

¥However, if you change the <html> element's font-size in the CSS you will see that everything else changes relative to it — both rem- and em-sized text.

线高单位

¥Line height units

lhrlh 是与 emrem 类似的相对长度单位。lhrlh 的区别在于,第一个是相对于元素本身的行高,而第二个是相对于根元素的行高,通常是 <html>

¥lh and rlh are relative lengths units similar to em and rem. The difference between lh and rlh is that the first one is relative to the line height of the element itself, while the second one is relative to the line height of the root element, usually <html>.

使用这些单位,我们可以精确地将框装饰与文本对齐。在此示例中,我们使用 lh 单位使用 repeating-linear-gradient() 创建类似记事本的线条。无论文本的行高是多少,行总是从正确的位置开始。

¥Using these units, we can precisely align box decoration to the text. In this example, we use lh unit to create notepad-like lines using repeating-linear-gradient(). It doesn't matter what's the line height of the text, the lines will always start in the right place.

css
body {
  margin: 0;
  display: grid;
  grid-template-columns: 1fr 1fr;
  padding: 24px;
  gap: 24px;
  background-color: floralwhite;
  font-family: sans-serif;
}

@supports not (height: 1lh) {
  body::before {
    grid-column: 1 / -1;
    padding: 8px;
    border-radius: 4px;
    background-color: tomato;
    color: white;
    content: "You browser doesn’t support lh unit just yet";
  }
}
css
p {
  margin: 0;
  background-image: repeating-linear-gradient(
    to top,
    lightskyblue 0 2px,
    transparent 2px 1lh
  );
}
html
<p style="line-height: 2em">
  Summer is a time for adventure, and this year was no exception. I had many
  exciting experiences, but two of my favorites were my trip to the beach and my
  week at summer camp.
</p>

<p style="line-height: 4em">
  At the beach, I spent my days swimming, collecting shells, and building
  sandcastles. I also went on a boat ride and saw dolphins swimming alongside
  us.
</p>

百分比

¥Percentages

在很多情况下,百分比的处理方式与长度相同。百分比的问题在于它们总是相对于其他值设置的。例如,如果将某个元素的 font-size 设置为百分比,则它将是该元素父元素的 font-size 的百分比。如果你对 width 值使用百分比,则它将是父级 width 的百分比。

¥In a lot of cases, a percentage is treated in the same way as a length. The thing with percentages is that they are always set relative to some other value. For example, if you set an element's font-size as a percentage, it will be a percentage of the font-size of the element's parent. If you use a percentage for a width value, it will be a percentage of the width of the parent.

在下面的示例中,两个百分比大小的框和两个像素大小的框具有相同的类名。这些集合的宽度分别为 40% 和 200px。

¥In the below example the two percentage-sized boxes and the two pixel-sized boxes have the same class names. The sets are 40% and 200px wide respectively.

不同之处在于第二组两个盒子位于 400 像素宽的封装器内。第二个 200 像素宽的框与第一个宽度相同,但第二个 40% 框现在是 400 像素的 40% — 比第一个窄很多!

¥The difference is that the second set of two boxes is inside a wrapper that is 400 pixels wide. The second 200px wide box is the same width as the first one, but the second 40% box is now 40% of 400px — a lot narrower than the first one!

尝试更改封装器的宽度或百分比值以查看其工作原理。

¥Try changing the width of the wrapper or the percentage value to see how this works.

下一个示例以百分比设置字体大小。每个 <li> 都有 80%的 font-size;因此,嵌套列表项会随着从父级继承其大小而逐渐变小。

¥The next example has font sizes set in percentages. Each <li> has a font-size of 80%; therefore, the nested list items become progressively smaller as they inherit their sizing from their parent.

请注意,虽然许多值类型接受长度或百分比,但有些值类型仅接受长度。你可以在 MDN 属性参考页面上查看接受哪些值。如果允许的值包括 <length-percentage>,则你可以使用长度或百分比。如果允许的值仅包括 <length>,则无法使用百分比。

¥Note that, while many value types accept a length or a percentage, there are some that only accept length. You can see which values are accepted on the MDN property reference pages. If the allowed value includes <length-percentage> then you can use a length or a percentage. If the allowed value only includes <length>, it is not possible to use a percentage.

数字

¥Numbers

某些值类型接受数字,但不添加任何单位。接受无单位数字的属性示例是 opacity 属性,它控制元素的不透明度(透明程度)。此属性接受 0(完全透明)和 1(完全不透明)之间的数字。

¥Some value types accept numbers, without any unit added to them. An example of a property which accepts a unitless number is the opacity property, which controls the opacity of an element (how transparent it is). This property accepts a number between 0 (fully transparent) and 1 (fully opaque).

在下面的示例中,尝试将 opacity 的值更改为 01 之间的各种十进制值,并查看框及其内容如何变得或多或少不透明。

¥In the below example, try changing the value of opacity to various decimal values between 0 and 1 and see how the box and its contents become more or less opaque.

注意:当你在 CSS 中使用数字作为值时,不应将其括在引号中。

¥Note: When you use a number in CSS as a value it should not be surrounded in quotes.

颜色

¥Color

颜色值可以在 CSS 中的许多地方使用,无论你是指定文本、背景、边框等的颜色。CSS 中设置颜色的方法有很多种,允许你控制大量令人兴奋的属性。

¥Color values can be used in many places in CSS, whether you are specifying the color of text, backgrounds, borders, and lots more. There are many ways to set color in CSS, allowing you to control plenty of exciting properties.

现代计算机中可用的标准颜色系统支持 24 位颜色,这允许通过不同的红色、绿色和蓝色通道的组合显示大约 1670 万种不同的颜色,每个通道有 256 个不同的值 (256 x 256 x 256 = 16,777,216)。

¥The standard color system available in modern computers supports 24-bit colors, which allows displaying about 16.7 million distinct colors via a combination of different red, green, and blue channels with 256 different values per channel (256 x 256 x 256 = 16,777,216).

在本节中,我们将首先了解指定颜色的最常见方法:使用关键字、十六进制和 rgb() 值。我们还将快速浏览其他颜色函数,使你能够在看到它们时识别它们或尝试不同的应用颜色方式。

¥In this section, we'll first look at the most commonly seen ways of specifying colors: using keywords, hexadecimal, and rgb() values. We'll also take a quick look at additional color functions, enabling you to recognize them when you see them or experiment with different ways of applying color.

你可能会决定一个调色板,然后在整个项目中使用这些颜色以及你最喜欢的指定颜色的方式。你可以混合和匹配颜色模型,但通常最好是你的整个项目使用相同的声明颜色的方法以保持一致性!

¥You will likely decide on a color palette and then use those colors — and your favorite way of specifying color — throughout your project. You can mix and match color models, but it's usually best if your entire project uses the same method of declaring colors for consistency!

颜色关键词

¥Color keywords

你将看到许多 MDN 代码示例中使用的颜色关键字(或 '命名颜色')。由于 <named-color> 数据类型包含的颜色值数量非常有限,因此这些颜色值在生产网站上并不常用。由于关键字将颜色表示为人类可读的文本值,因此在代码示例中使用命名颜色来清楚地告诉用户期望什么颜色,以便学习者可以专注于正在教授的内容。

¥You will see the color keywords (or 'named colors') used in many MDN code examples. As the <named-color>s data type contains a very finite number of color values, these are not commonly used on production websites. As the keyword represents the color as a human-readable text value, named colors are used in code examples to clearly tell the user what color is expected so the learner can focus on the content being taught.

尝试在下面的实例中使用不同的颜色值,以更多地了解它们的工作原理。

¥Try playing with different color values in the live examples below, to get more of an idea how they work.

十六进制 RGB 值

¥Hexadecimal RGB values

你可能遇到的下一种颜色值是十六进制代码。十六进制使用 0-9a-f 中的 16 个字符,因此整个范围是 0123456789abcdef。每个十六进制颜色值由一个哈希/井号符号 (#) 后跟三个或六个十六进制字符(例如 #fcc#ffc0cb)组成,可选的一或两个十六进制字符代表前三个或六个字符的 alpha 透明度 颜色值。

¥The next type of color value you are likely to encounter is hexadecimal codes. Hexadecimal uses 16 characters from 0-9 and a-f, so the entire range is 0123456789abcdef. Each hex color value consists of a hash/pound symbol (#) followed by three or six hexadecimal characters (#fcc or #ffc0cb, for example), with an optional one or two hexadecimal characters representing the alpha-transparency of the previous three or six character color values.

当使用十六进制来描述 RGB 值时,每对十六进制字符都是代表通道之一(红色、绿色和蓝色)的十进制数字,并允许我们为每个通道指定 256 个可用值中的任意值 (16 x 16 = 256)。这些值不如定义颜色的关键字直观,但它们的用途要广泛得多,因为你可以用它们表示任何 RGB 颜色。

¥When using hexadecimal to describe RGB values, each pair of hexadecimal characters is a decimal number representing one of the channels — red, green and blue — and allows us to specify any of the 256 available values for each (16 x 16 = 256). These values are less intuitive than keywords for defining colors, but they are a lot more versatile because you can represent any RGB color with them.

再次尝试更改值以查看颜色如何变化。

¥Again, try changing the values to see how the colors vary.

RGB 值

¥RGB values

要直接创建 RGB 值,rgb() 函数采用三个参数代表颜色的红色、绿色和蓝色通道值,可选的第四个值由表示不透明度的斜线 ('/') 分隔,与十六进制值的方式非常相似。与 RGB 的区别在于,每个通道不是由两个十六进制数字表示,而是由 0 到 255 之间的十进制数字或 0% 到 100%(包括 0% 和 100%)之间的百分比表示(但不是两者的混合)。

¥To create RGB values directly, the rgb() function takes three parameters representing red, green, and blue channel values of the colors, with an optional fourth value separated by a slash ('/') representing opacity, in much the same way as hex values. The difference with RGB is that each channel is represented not by two hex digits, but by a decimal number between 0 and 255 or a percent between 0% and 100% inclusive (but not a mixture of the two).

让我们重写最后一个示例以使用 RGB 颜色:

¥Let's rewrite our last example to use RGB colors:

你可以将第四个参数传递给 rgb(),它表示颜色的 Alpha 通道,用于控制不透明度。如果将此值设置为 0,它将使颜色完全透明,而 1 将使其完全不透明。介于两者之间的值可提供不同级别的透明度。

¥You can pass a fourth parameter to rgb(), which represents the alpha channel of the color, which controls opacity. If you set this value to 0 it will make the color fully transparent, whereas 1 will make it fully opaque. Values in between give you different levels of transparency.

注意:在颜色上设置 Alpha 通道与使用我们之前看到的 opacity 属性有一个关键区别。当你使用不透明度时,你会使元素及其内部的所有内容变得不透明,而使用带有 alpha 参数颜色的 RGB 只会使你指定的颜色变得不透明。

¥Note: Setting an alpha channel on a color has one key difference to using the opacity property we looked at earlier. When you use opacity you make the element and everything inside it opaque, whereas using RGB with an alpha parameter colors only makes the color you are specifying opaque.

在下面的示例中,我们将背景图片添加到彩色框的包含块中。然后,我们将框设置为具有不同的不透明度值 - 请注意当 Alpha 通道值较小时,背景如何显示得更多。

¥In the example below, we have added a background image to the containing block of our colored boxes. We have then set the boxes to have different opacity values — notice how the background shows through more when the alpha channel value is smaller.

在此示例中,尝试更改 Alpha 通道值以查看它如何影响颜色输出。

¥In this example, try changing the alpha channel values to see how it affects the color output.

注意:在旧版本的 CSS 中,rgb() 语法不支持 alpha 参数 - 为此,你需要使用一个名为 rgba() 的不同函数。现在你可以将 alpha 参数传递给 rgb()rgba() 函数是 rgb() 的别名。

¥Note: In older versions of CSS, the rgb() syntax didn't support an alpha parameter - you needed to use a different function called rgba() for that. These days you can pass an alpha parameter to rgb(). The rgba() function is an alias for rgb().

SRGB 值

¥SRGB values

sRGB 色彩空间定义红色 (r)、绿色 (g) 和蓝色 (b) 色彩空间中的颜色。

¥The sRGB color space defines colors in the red (r), green (g), and blue (b) color space.

使用色调来指定颜色

¥Using hues to specify a color

如果你想要超越关键字、十六进制和 rgb() 的颜色,你可能需要尝试使用 <hue>。色调是让我们能够区分红色、橙色、黄色、绿色、蓝色等颜色之间差异或相似性的属性。关键概念是你可以在 <angle> 中指定色调,因为大多数颜色模型使用以下方式描述色调 一个 color wheel

¥If you want to go beyond keywords, hexadecimal, and rgb() for colors, you might want to try using <hue>. Hue is the property that allows us to tell the difference or similarity between colors like red, orange, yellow, green, blue, etc. The key concept is that you can specify a hue in an <angle> because most of the color models describe hues using a color wheel.

有多种颜色函数包含 <hue> 分量,包括 hsl()hwb()lch()。其他颜色函数(例如 lab())根据人类可以看到的内容定义颜色。

¥There are several color functions that include a <hue> component, including hsl(),hwb(), and lch(). Other color functions, like lab(), define colors based on what humans can see.

如果你想了解有关这些函数和颜色空间的更多信息,请参阅 使用 CSS 将颜色应用于 HTML 元素 指南、列出了在 CSS 中使用颜色的所有不同方式的 <color> 参考以及提供 CSS 中所有颜色类型概述的 CSS 颜色模块CSS 颜色模块。 使用颜色值的属性。

¥If you want to find out more about these functions and color spaces, see the Applying color to HTML elements using CSS guide, the <color> reference that lists all the different ways you can use colors in CSS, and the CSS color module that provides an overview of all the color types in CSS and the properties that use color values.

HWB

在 CSS 中使用色调的一个很好的起点是指定 srgb() 颜色的 hwb() 函数。这三个部分是:

¥A great starting point for using hues in CSS is the hwb() function which specifies an srgb() color. The three parts are:

  • 色调:颜色的基础色调。这采用 0 到 360 之间的 <hue> 值,表示色轮周围的角度。
  • 白度:颜色有多白?该值介于 0%(无白度)和 100%(全白度)之间。
  • 黑:颜色有多黑?该值的范围是 0%(无黑色)到 100%(全黑色)。

HSL

hwb() 函数类似的是 hsl() 函数,它也指定 srgb() 颜色。HSL 除了使用 SaturationLightness 之外,还使用 Hue

¥Similar to the hwb() function is the hsl() function which also specifies an srgb() color. HSL uses Hue, in addition to Saturation and Lightness:

  • 色调
  • 饱和:颜色的饱和度如何?它采用 0-100% 之间的值,其中 0 表示无颜色(它将显示为灰色阴影),100% 表示全色饱和度。
  • 亮度:颜色有多浅或多亮?该值取 0-100% 之间的值,其中 0 表示无光(将显示为全黑),100% 为全光(将显示为全白)。

hsl() 颜色值还有一个可选的第四个值,与颜色用斜线 (/) 分隔,表示 alpha 透明度。

¥The hsl() color value also has an optional fourth value, separated from the color with a slash (/), representing the alpha transparency.

让我们更新 RGB 示例以使用 HSL 颜色:

¥Let's update the RGB example to use HSL colors instead:

就像 rgb() 一样,你可以将 alpha 参数传递给 hsl() 来指定不透明度:

¥Just like with rgb() you can pass an alpha parameter to hsl() to specify opacity:

注意:在旧版本的 CSS 中,hsl() 语法不支持 alpha 参数 - 为此,你需要使用一个名为 hsla() 的不同函数。如今,你可以将 alpha 参数传递给 hsl(),但为了向后兼容旧网站,仍然支持 hsla() 语法,并且具有与 hsl() 完全相同的行为。

¥Note: In older versions of CSS, the hsl() syntax didn't support an alpha parameter - you needed to use a different function called hsla() for that. These days you can pass an alpha parameter to hsl(), but for backwards compatibility with old websites, the hsla() syntax is still supported, and has exactly the same behavior as hsl().

图片

¥Images

只要图片是有效值,就会使用 <image> 值类型。这可以是通过 url() 函数或渐变指向的实际图片文件。

¥The <image> value type is used wherever an image is a valid value. This can be an actual image file pointed to via a url() function, or a gradient.

在下面的示例中,我们演示了用作 CSS background-image 属性值的图片和渐变。

¥In the example below, we have demonstrated an image and a gradient in use as a value for the CSS background-image property.

注意:<image> 还有一些其他可能的值,但是这些值较新,并且当前浏览器支持较差。如果你想了解有关 <image> 数据类型的信息,请查看 MDN 上的页面。

¥Note: There are some other possible values for <image>, however these are newer and currently have poor browser support. Check out the page on MDN for the <image> data type if you want to read about them.

位置

¥Position

<position> 值类型表示一组 2D 坐标,用于定位背景图片等项目(通过 background-position)。它可以使用 topleftbottomrightcenter 等关键字将项目与 2D 框的特定边界以及长度(表示距框的顶部和左侧边缘的偏移量)对齐。

¥The <position> value type represents a set of 2D coordinates, used to position an item such as a background image (via background-position). It can take keywords such as top, left, bottom, right, and center to align items with specific bounds of a 2D box, along with lengths, which represent offsets from the top and left-hand edges of the box.

典型的位置值由两个值组成 - 第一个值水平设置位置,第二个值垂直设置。如果你仅指定一个轴的值,则另一轴将默认为 center

¥A typical position value consists of two values — the first sets the position horizontally, the second vertically. If you only specify values for one axis the other will default to center.

在下面的示例中,我们使用关键字将背景图片放置在距容器顶部和右侧 40 像素的位置。

¥In the following example we have positioned a background image 40px from the top and to the right of the container using a keyword.

尝试使用这些值,看看如何推动图片。

¥Play around with these values to see how you can push the image around.

字符串和标识符

¥Strings and identifiers

在上面的示例中,我们已经看到了关键字用作值的地方(例如 <color> 关键字,如 redblackrebeccapurplegoldenrod)。这些关键字更准确地描述为标识符,CSS 理解的特殊值。因此,它们不被引用 - 它们不被视为字符串。

¥Throughout the examples above, we've seen places where keywords are used as a value (for example <color> keywords like red, black, rebeccapurple, and goldenrod). These keywords are more accurately described as identifiers, a special value that CSS understands. As such they are not quoted — they are not treated as strings.

CSS 中有些地方需要使用字符串。例如,指定生成的内容时。在本例中,该值被引用以表明它是一个字符串。在下面的示例中,我们使用不带引号的颜色关键字以及带引号的生成内容字符串。

¥There are places where you use strings in CSS. For example, when specifying generated content. In this case, the value is quoted to demonstrate that it is a string. In the example below, we use unquoted color keywords along with a quoted generated content string.

函数

¥Functions

在编程中,函数是执行特定任务的一段代码。函数很有用,因为你可以编写一次代码,然后多次重复使用它,而不是一遍又一遍地编写相同的逻辑。大多数编程语言不仅支持函数,还为常见任务提供了方便的内置函数,因此你不必从头开始编写它们。

¥In programming, a function is a piece of code that does a specific task. Functions are useful because you can write code once, then reuse it many times instead of writing the same logic over and over. Most programming languages not only support functions but also come with convenient built-in functions for common tasks so you don't have to write them yourself from scratch.

CSS 也有 functions,其工作方式与其他语言中的函数类似。事实上,我们已经在上面的 颜色 部分中看到了 CSS 函数以及 rgb()hsl() 函数。

¥CSS also has functions, which work in a similar way to functions in other languages. In fact, we've already seen CSS functions in the Color section above with rgb() and hsl() functions.

除了应用颜色之外,你还可以使用 CSS 中的函数来做很多其他事情。例如,变换函数 是在页面上移动、旋转和缩放元素的常见方法。你可能会看到 translate() 表示水平或垂直移动某物,rotate() 表示旋转某物,或者 scale() 表示使某物变大或变小。

¥Aside from applying colors, you can use functions in CSS to do a lot of other things. For example Transform functions are a common way to move, rotate, and scale elements on a page. You might see translate() for moving something horizontally or vertically, rotate() to rotate something, or scale() to make something bigger or smaller.

数学函数

¥Math functions

当你为项目创建样式时,你可能会从数字开始,例如 300px 表示长度或 200ms 表示持续时间。如果你想让这些值根据其他值进行更改,则需要进行一些数学计算。你可以计算一个值的百分比或将一个数字添加到另一个数字,然后使用结果更新你的 CSS。

¥When you are creating styles for a project, you will probably start off with numbers like 300px for lengths or 200ms for durations. If you want to have these values change based on other values, you will need to do some math. You could calculate the percentage of a value or add a number to another number, then update your CSS with the result.

CSS 支持 数学函数,这使我们能够执行计算,而不是依赖静态值或在 JavaScript 中进行数学运算。最常见的数学函数之一是 calc(),它可以让你执行加法、减法、乘法和除法等运算。

¥CSS has support for Math functions, which allow us to perform calculations instead of relying on static values or doing the math in JavaScript. One of the most common math functions is calc() which lets you do operations like addition, subtraction, multiplication, and division.

例如,假设我们想要将元素的宽度设置为其父容器的 20% 加 100px。我们无法使用静态值指定此宽度 - 如果父级使用百分比宽度(或相对单位,如 emrem),那么它将根据其使用的上下文以及其他因素(例如用户的设备)而变化 或浏览器窗口宽度。但是,我们可以使用 calc() 将元素的宽度设置为其父容器的 20% 加 100px。20% 基于父容器 (.wrapper) 的宽度,如果该宽度发生变化,计算也会发生变化:

¥For example, let's say we want to set the width of an element to be 20% of its parent container plus 100px. We can't specify this width with a static value — if the parent uses a percentage width (or a relative unit like em or rem) then it will vary depending on the context it is used in, and other factors such as the user's device or browser window width. However, we can use calc() to set the width of the element to be 20% of its parent container plus 100px. The 20% is based on the width of the parent container (.wrapper) and if that width changes, the calculation will change too:

CSS 中还可以使用许多其他数学函数,例如 min()max()clamp();这些分别允许你从一组值中选择最小、最大或中间值。你还可以像 sin()cos()tan() 一样使用 三角函数 来计算围绕点旋转元素的角度,或者选择以 色相角 作为参数的颜色。当你需要对某物的移动和外观进行非常具体的控制时,指数函数 也可以用于动画和过渡。

¥There are many other math functions that you can use in CSS, such as min(), max(), and clamp(); respectively these let you pick the smallest, largest, or middle value from a set of values. You can also use Trigonometric functions like sin(), cos(), and tan() to calculate angles for rotating elements around a point, or choose colors that take a hue angle as a parameter. Exponential functions might also be used for animations and transitions, when you require very specific control over how something moves and looks.

了解 CSS 函数很有用,这样你在看到它们时就能认出它们。你应该开始在你的项目中尝试它们 - 它们将帮助你避免编写自定义或重复代码来实现使用常规 CSS 可以获得的结果。

¥Knowing about CSS functions is useful so you recognize them when you see them. You should start experimenting with them in your projects — they will help you avoid writing custom or repetitive code to achieve results that you can get with regular CSS.

测试你的技能!

¥Test your skills!

你已读完本文,但你还记得最重要的信息吗?在继续之前,你可以找到一些进一步的测试来验证你是否已保留此信息 - 请参阅 测试你的技能:数值和单位

¥You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: Values and units.

概括

¥Summary

这是你可能遇到的最常见的值和单位类型的快速浏览。你可以在 CSS 值和单位 参考页上查看所有不同类型 - 在学习这些课程时你会遇到许多正在使用的类型。

¥This has been a quick run-through of the most common types of values and units you might encounter. You can have a look at all of the different types on the CSS Values and units reference page — you will encounter many of these in use as you work through these lessons.

要记住的关键是每个属性都有一个定义的允许值类型列表,并且每个值类型都有一个定义来解释这些值是什么。然后你可以在 MDN 上查找具体信息。例如,了解 <image> 还允许你创建颜色渐变是有用的,但可能不是显而易见的知识!

¥The key thing to remember is that each property has a defined list of allowed value types, and each value type has a definition explaining what the values are. You can then look up the specifics here on MDN. For example, understanding that <image> also allows you to create a color gradient is useful but perhaps non-obvious knowledge to have!

在下一篇文章中,我们将看看 CSS 中的 物品尺寸 是如何实现的。

¥In the next article, we'll take a look at how items are sized in CSS.