背景和边框
在本课程中,我们将了解一些可以使用 CSS 背景和边框进行的创意操作。通过添加渐变、背景图片和圆角、背景和边框,可以解决 CSS 中的许多样式问题。
¥In this lesson, we will take a look at some of the creative things you can do with CSS backgrounds and borders. From adding gradients, background images, and rounded corners, backgrounds and borders are the answer to a lot of styling questions in CSS.
在 CSS 中设置背景样式
¥Styling backgrounds in CSS
CSS background
属性是我们将在本课中遇到的许多背景普通属性的简写。如果你在样式表中发现复杂的背景属性,可能看起来有点难以理解,因为一次可以传入如此多的值。
¥The CSS background
property is a shorthand for a number of background longhand properties that we will meet in this lesson. If you discover a complex background property in a stylesheet, it might seem a little hard to understand as so many values can be passed in at once.
.box {
background:
linear-gradient(
105deg,
rgb(255 255 255 / 20%) 39%,
rgb(51 56 57 / 100%) 96%
)
center center / 400px 200px no-repeat,
url(big-star.png) center no-repeat,
rebeccapurple;
}
我们将在本教程后面讨论速记的工作原理,但首先让我们通过查看各个背景属性来了解一下可以对 CSS 中的背景执行的不同操作。
¥We'll return to how the shorthand works later in the tutorial, but first let's have a look at the different things you can do with backgrounds in CSS, by looking at the individual background properties.
背景颜色
¥Background colors
background-color
属性定义 CSS 中任何元素的背景颜色。该酒店接受任何有效的 <color>
。background-color
延伸到元素的内容和填充框下方。
¥The background-color
property defines the background color on any element in CSS. The property accepts any valid <color>
. A background-color
extends underneath the content and padding box of the element.
在下面的示例中,我们使用了各种颜色值来向框、标题和 <span>
元素添加背景颜色。
¥In the example below, we have used various color values to add a background color to the box, a heading, and a <span>
element.
使用任何可用的 <color>
值来尝试这些。
¥Play around with these, using any available <color>
value.
背景图片
¥Background images
background-image
属性允许在元素的背景中显示图片。在下面的例子中,我们有两个框 — 一个的背景图片大于框 (balloons.jpg)。另一个有单个星星的小图片(star.png)。
¥The background-image
property enables the display of an image in the background of an element. In the example below, we have two boxes — one has a background image that is larger than the box (balloons.jpg). The other has a small image of a single star (star.png).
此示例演示了有关背景图片的两件事。默认情况下,大图片不会缩小以适应框,因此我们只能看到它的一个小角,而小图片会平铺以填充框。
¥This example demonstrates two things about background images. By default, the large image is not scaled down to fit the box, so we only see a small corner of it, whereas the small image is tiled to fill the box.
如果除了背景图片之外还指定背景颜色,则图片将显示在该颜色之上。尝试向上面的示例添加 background-color
属性以查看其实际效果。
¥If you specify a background color in addition to a background image then the image displays on top of the color. Try adding a background-color
property to the example above to see that in action.
控制背景重复
¥Controlling background-repeat
background-repeat
属性用于控制图片的平铺行为。可用值为:
¥The background-repeat
property is used to control the tiling behavior of images. The available values are:
no-repeat
— 停止背景完全重复。repeat-x
— 水平重复。repeat-y
— 垂直重复。repeat
- 默认值;在两个方向重复。space
— 重复尽可能多的次数,如果有额外的可用空间,则在图片之间添加空间。round
— 与space
类似,但拉伸图片以填充任何额外的空间
在下面的示例中尝试这些值。我们已将值设置为 no-repeat
,因此你只会看到一颗星星。尝试不同的值 - repeat-x
和 repeat-y
- 看看它们的效果如何。
¥Try these values out in the example below. We have set the value to no-repeat
so you will only see one star. Try out the different values — repeat-x
and repeat-y
— to see what their effects are.
调整背景图片的大小
¥Sizing the background image
初始背景图片示例中使用的 balloons.jpg 图片是一张大图片,由于大于其背景元素而被裁剪。在这种情况下,我们可以使用 background-size
属性(可以采用 <length>
或 <percentage>
值)来调整图片大小以适合背景。
¥The balloons.jpg image used in the initial background image example is a large image that was cropped due to being larger than the element it is a background of. In this case, we could use the background-size
property, which can take <length>
or <percentage>
values, to size the image to fit inside the background.
你还可以使用关键字:
¥You can also use keywords:
cover
— 浏览器将使图片足够大,以便它完全覆盖框区域,同时仍保留其 aspect ratio。在这种情况下,图片的一部分可能最终会超出盒子的范围。contain
— 浏览器会将图片调整为适合框内的大小。在这种情况下,如果图片的纵横比与框的纵横比不同,则图片的两侧或顶部和底部可能会出现间隙。
在下面的示例中,balloons.jpg 图片的长度单位设置为框内的大小。你可以看到这扭曲了图片。
¥In the example below, the balloons.jpg image has length units set to size it inside the box. You can see this has distorted the image.
尝试以下操作。
¥Try the following.
- 更改用于修改背景大小的长度单位。
- 删除长度单位,看看使用
background-size: cover
或background-size: contain
时会发生什么。 - 如果你的图片比框小,你可以更改
background-repeat
的值以重复图片。
定位背景图片
¥Positioning the background image
background-position
属性允许你选择背景图片在其应用到的框中出现的位置。它使用的坐标系中,框的左上角为 (0,0)
,框沿水平 (x
) 和垂直 (y
) 轴定位。
¥The background-position
property allows you to choose the position in which the background image appears on the box it is applied to. This uses a coordinate system in which the top-left-hand corner of the box is (0,0)
, and the box is positioned along the horizontal (x
) and vertical (y
) axes.
注意:默认
background-position
值为(0,0)
。¥Note: The default
background-position
value is(0,0)
.
最常见的 background-position
值采用两个单独的值 - 一个水平值,后跟一个垂直值。
¥The most common background-position
values take two individual values — a horizontal value followed by a vertical value.
你可以使用诸如 top
和 right
之类的关键字(在 background-position
页面上查找其他关键字):
¥You can use keywords such as top
and right
(look up the others on the background-position
page):
.box {
background-image: url(star.png);
background-repeat: no-repeat;
background-position: top center;
}
还有 lengths
和 percentages
:
¥And lengths
, and percentages
:
.box {
background-image: url(star.png);
background-repeat: no-repeat;
background-position: 20px 10%;
}
你还可以将关键字值与长度或百分比混合,在这种情况下,第一个值必须引用水平位置或偏移量,第二个值必须引用垂直位置。例如:
¥You can also mix keyword values with lengths or percentages, in which case the first value must refer to the horizontal position or offset and the second vertical. For example:
.box {
background-image: url(star.png);
background-repeat: no-repeat;
background-position: 20px top;
}
最后,你还可以使用 4 值语法来指示与框某些边缘的距离 - 在这种情况下,长度单位是与其前面的值的偏移量。因此,在下面的 CSS 中,我们将背景定位为距离顶部 20 像素,距离右侧 10 像素:
¥Finally, you can also use a 4-value syntax to indicate a distance from certain edges of the box — the length unit, in this case, is an offset from the value that precedes it. So in the CSS below we are positioning the background 20px from the top and 10px from the right:
.box {
background-image: url(star.png);
background-repeat: no-repeat;
background-position: top 20px right 10px;
}
使用下面的示例来尝试这些值并在框内移动星星。
¥Use the example below to play around with these values and move the star around inside the box.
注意:
background-position
是background-position-x
和background-position-y
的简写,允许你单独设置不同的轴位置值。¥Note:
background-position
is a shorthand forbackground-position-x
andbackground-position-y
, which allow you to set the different axis position values individually.
渐变背景
¥Gradient backgrounds
渐变(当用于背景时)的作用就像图片一样,也是通过使用 background-image
属性来设置的。
¥A gradient — when used for a background — acts just like an image and is also set by using the background-image
property.
你可以在 <gradient>
数据类型的 MDN 页面上详细了解不同类型的渐变以及可以使用它们执行的操作。玩渐变的一种有趣方法是使用网络上提供的众多 CSS 渐变生成器之一,例如 CSSGradient.io。你可以创建一个渐变并复制和粘贴生成它的源代码。
¥You can read more about the different types of gradients and things you can do with them on the MDN page for the <gradient>
data type. A fun way to play with gradients is to use one of the many CSS Gradient Generators available on the web, such as CSSGradient.io. You can create a gradient and copy and paste the source code that generates it.
在下面的示例中尝试一些不同的渐变。在两个盒子中,我们分别有一个在整个盒子上拉伸的线性渐变,以及一个具有设定大小的径向渐变,因此会重复。
¥Try some different gradients in the example below. In the two boxes respectively, we have a linear gradient that is stretched over the whole box, and a radial gradient with a set size, which therefore repeats.
多个背景图片
¥Multiple background images
也可以有多个背景图片 - 你在单个属性值中指定多个 background-image
值,并用逗号分隔每个值。
¥It is also possible to have multiple background images — you specify multiple background-image
values in a single property value, separating each one with a comma.
当你执行此操作时,你最终可能会看到背景图片相互重叠。背景将与堆栈底部最后列出的背景图片分层,并且每个先前的图片堆叠在代码中紧随其后的图片的顶部。
¥When you do this you may end up with background images overlapping each other. The backgrounds will layer with the last listed background image at the bottom of the stack, and each previous image stacking on top of the one that follows it in the code.
注意:渐变可以与常规背景图片愉快地混合。
¥Note: Gradients can be happily mixed with regular background images.
其他 background-*
属性也可以像 background-image
一样具有逗号分隔值:
¥The other background-*
properties can also have comma-separated values in the same way as background-image
:
background-image: url(image1.png), url(image2.png), url(image3.png),
url(image4.png);
background-repeat: no-repeat, repeat-x, repeat;
background-position:
10px 20px,
top right;
不同属性的每个值将与其他属性中相同位置的值匹配。例如,上面的 image1
的 background-repeat
值将是 no-repeat
。但是,当不同的属性具有不同数量的值时会发生什么?答案是较小数量的值将循环 - 在上面的示例中,有四个背景图片,但只有两个 background-position
值。前两个位置值将应用于前两个图片,然后它们将再次循环 - image3
将被赋予第一个位置值,image4
将被赋予第二个位置值。
¥Each value of the different properties will match up to the values in the same position in the other properties. Above, for example, image1
's background-repeat
value will be no-repeat
. However, what happens when different properties have different numbers of values? The answer is that the smaller numbers of values will cycle — in the above example there are four background images but only two background-position
values. The first two position values will be applied to the first two images, then they will cycle back around again — image3
will be given the first position value, and image4
will be given the second position value.
让我们玩。下面的示例包含两个背景图片。要演示堆叠顺序,请尝试切换列表中最先出现的背景图片。或者使用其他属性来更改位置、大小或重复值。
¥Let's play. The example below includes two background images. To demonstrate the stacking order, try switching which background image comes first in the list. Or play with the other properties to change the position, size, or repeat values.
背景附件
¥Background attachment
我们为背景提供的另一个选项是指定内容滚动时背景如何滚动。这是使用 background-attachment
属性控制的,该属性可以采用以下值:
¥Another option we have available for backgrounds is specifying how they scroll when the content scrolls. This is controlled using the background-attachment
property, which can take the following values:
scroll
:当页面滚动时,导致元素的背景滚动。如果元素内容滚动,背景不会移动。实际上,背景固定在页面上的同一位置,因此它会随着页面滚动而滚动。fixed
:使元素的背景固定到视口,以便在滚动页面或元素内容时它不会滚动。它将始终保持在屏幕上的相同位置。local
:将背景固定到它所设置的元素上,因此当你滚动该元素时,背景也会随之滚动。
background-attachment
属性仅在有内容滚动时才起作用,因此我们制作了一个演示来演示这三个值之间的差异 - 看看 background-attachment.html(这里还有 查看源代码)。
¥The background-attachment
property only has an effect when there is content to scroll, so we've made a demo to demonstrate the differences between the three values — have a look at background-attachment.html (also see the source code here).
使用后台简写属性
¥Using the background shorthand property
正如本课程开头提到的,你经常会看到使用 background
属性指定的背景。这种简写方式可以让你一次设置所有不同的属性。
¥As mentioned at the beginning of this lesson, you will often see backgrounds specified using the background
property. This shorthand lets you set all of the different properties at once.
如果使用多个背景,你需要指定第一个背景的所有属性,然后在逗号后面添加下一个背景。在下面的示例中,我们有一个具有大小和位置的渐变,然后是具有 no-repeat
和位置的图片背景,然后是颜色。
¥If using multiple backgrounds, you need to specify all of the properties for the first background, then add your next background after a comma. In the example below we have a gradient with a size and position, then an image background with no-repeat
and a position, then a color.
编写背景图片简写值时需要遵循一些规则,例如:
¥There are a few rules that need to be followed when writing background image shorthand values, for example:
background-color
只能在最后一个逗号后指定。background-size
的值只能紧接在background-position
之后包含,并用 '/' 字符分隔,如下所示:center/80%
。
查看 background
的 MDN 页面以了解所有注意事项。
¥Take a look at the MDN page for background
to see all of the considerations.
背景的可访问性考虑
¥Accessibility considerations with backgrounds
将文本放置在背景图片或颜色之上时,你应该注意有足够的 contrast 以使访问者能够清晰地阅读文本。如果指定图片,并且文本将放置在该图片的顶部,你还应该指定 background-color
,以便在图片未加载时文本清晰可见。
¥When placing text on top of a background image or color, you should take care that you have enough contrast for the text to be legible for your visitors. If specifying an image, and if text will be placed on top of that image, you should also specify a background-color
that will allow the text to be legible if the image does not load.
屏幕阅读器无法解析背景图片;因此,它们应该纯粹是装饰。任何重要的内容都应该是 HTML 页面的一部分,而不是包含在背景中。
¥Screen readers cannot parse background images; therefore, they should be purely decoration. Any important content should be part of the HTML page and not contained in a background.
边框
¥Borders
在学习盒子模型时,我们发现边界如何影响盒子的大小。在本课中,我们将了解如何创造性地使用边框。通常,当我们使用 CSS 向元素添加边框时,我们会使用一个简写属性,在一行 CSS 中设置边框的颜色、宽度和 style。
¥When learning about the Box Model, we discovered how borders affect the size of our box. In this lesson, we will look at how to use borders creatively. Typically when we add borders to an element with CSS we use a shorthand property that sets the color, width, and style of the border in one line of CSS.
我们可以使用 border
为盒子的所有四个边设置边框:
¥We can set a border for all four sides of a box with border
:
.box {
border: 1px solid black;
}
或者我们可以瞄准盒子的一个边缘,例如:
¥Or we can target one edge of the box, for example:
.box {
border-top: 1px solid black;
}
各个属性包括 border-width
、border-style
和 border-color
简写属性:
¥The individual properties include the border-width
, border-style
, and border-color
shorthand properties:
.box {
border-width: 1px;
border-style: solid;
border-color: black;
}
四个边的宽度、样式和颜色都有普通属性:
¥There are longhand properities for width, style, and color for each of the four sides:
.box {
border-top-width: 1px;
border-top-style: solid;
border-top-color: black;
}
注意:这些上、右、下和左边框属性还映射了与文档的书写模式相关的 逻辑边界属性(例如,从左到右或从右到左文本,或从上到下)。我们将在下一课(涵盖 处理不同的文本方向)中探讨这些内容。
¥Note: These top, right, bottom, and left border properties also have mapped logical border properties that relate to the writing mode of the document (e.g. left-to-right or right-to-left text, or top-to-bottom). We'll be exploring these in the next lesson, which covers handling different text directions.
你可以使用多种样式作为边框。在下面的示例中,我们为框使用了两种不同的边框样式,为标题使用了两种不同的边框样式。尝试使用边框样式、宽度和颜色来了解边框的工作原理。
¥There are a variety of styles that you can use for borders. In the example below, we have used two different border styles for the box and two different border styles for the heading. Play with the border style, width, and color to see how borders work.
圆角
¥Rounded corners
使用 border-radius
属性和与框的每个角相关的相关长手来实现框的圆角。两个长度或百分比可以用作值,第一个值定义水平半径,第二个值定义垂直半径。在很多情况下,你只会传递一个值,该值将用于两者。
¥Rounding corners on a box is achieved by using the border-radius
property and associated longhands that relate to each corner of the box. Two lengths or percentages may be used as a value, the first value defining the horizontal radius, and the second the vertical radius. In a lot of cases, you will only pass in one value, which will be used for both.
例如,要使盒子的所有四个角的半径均为 10px:
¥For example, to make all four corners of a box have a 10px radius:
.box {
border-radius: 10px;
}
或者使右上角的水平半径为 1em
,垂直半径为 10%:
¥Or to make the top right corner have a horizontal radius of 1em
, and a vertical radius of 10%:
.box {
border-top-right-radius: 1em 10%;
}
注意:与上面的边框属性一样,这些边框半径属性也映射了 逻辑边框半径属性。
¥Note: Like with the border properties above, these border-radius properties also have mapped logical border-radius properties.
我们在下面的示例中设置了所有四个角,然后更改了右上角的值以使其不同。你可以使用这些值来更改角。查看 border-radius
的属性页以查看可用的语法选项。边界半径生成器 可用于为你输出圆角值。
¥We have set all four corners in the example below and then changed the values for the top right corner to make it different. You can play with the values to change the corners. Take a look at the property page for border-radius
to see the available syntax options. The border-radius generator can be used to output rounded corner values for you.
测试你的技能!
¥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: Backgrounds and borders.
概括
¥Summary
我们在这里已经介绍了很多内容,你可以看到向框添加背景或边框有很多内容。如果你想了解有关此处讨论的任何功能的更多信息,请探索不同的属性页面。MDN 上几乎每个页面都有示例供你使用,以增强你的知识。
¥We have covered quite a lot here, and you can see that there is quite a lot to adding a background or a border to a box. Do explore the different property pages if you want to find out more about any of the features discussed here. Almost every page on MDN has examples for you to play with to enhance your knowledge.
在下一篇文章中,我们将了解文档的书写模式如何与 CSS 交互。当文本不从左向右流动时会发生什么?
¥In the next article, we'll find out how the writing mode of your document interacts with your CSS. What happens when the text does not flow from left to right?