大家好,我是翼同学!

今天笔记的内容是:
通过CSS背景属性,可以为页面元素添加背景样式。
常见的背景样式有背景颜色、背景图片、背景平铺、背景图片位置以及背景固定等内容。
一般的,页面元素的颜色默认为透明的(transparent),我们可以通过background-color属性可以定义元素的背景颜色。
举个例子:
<head>
<style>
body {
background-color: skyblue;
}
style>
head>
<body>
<h1>滁州西涧h1>
<p>
独怜幽草涧边生,上有黄鹂深树鸣。
p>
<p>
春潮带雨晚来急,野渡无人舟自横。
p>
body>
html>
效果如下:

background-image属性描述了元素的背景图像。在实际开发中,会将一些logo之类的图片设置为背景。这种方式的优点在于容易控制图片位置。
语法为:
background-image: url(这里填绝对地址或相对地址指定背景图像);
默认情况下是没有背景图片的。(background-image: none)
需要注意的是,当我们设置背景图像后,默认情况下背景图片是平铺的。效果如下:
<head>
<style>
body {
background-image: url(images.png);
}
style>
head>
<body>
<h1>Hello World!h1>
body>
html>

因此,我们可以通过background-repeat属性的不同取值来设置图像如何平铺或者不平铺。具体看下表:
| 参数值 | 含义 |
|---|---|
repeat | 背景平铺(默认情况下就是平铺的) |
no-repeat | 背景不平铺 |
repeat-x | 背景沿着x轴平铺 |
repeat-y | 背景沿着y轴平铺 |
下面举例:
<head>
<style>
body {
background-image: url(images.png);
background-repeat: no-repeat;
}
style>
head>
<body>
<h1>Hello World!h1>
body>
html>

<head>
<style>
body {
background-image: url(images.png);
background-repeat: repeat-x;
}
style>
head>
<body>
<h1>Hello World!h1>
body>
html>

通过background-attachment属性可以设置背景图像是否固定或者随页面其余部分滚动。(可制作视差滚动效果)
background-attachment属性有两个取值,具体如下所示:
| 参数 | 作用 |
|---|---|
scroll | 背景图像随着对象内容滚动 |
fixed | 背景图像固定 |
效果如下所示:
一、无固定

二、有固定

通过background-position属性可以设置图像在背景中的位置。
语法为:
background-position: x y;
需要注意到,这里的x坐标和y坐标可以是方位名词也可以是精确单位。具体看下表:
| 坐标形式 | 取值 | 含义 |
|---|---|---|
| 方位名词 | top、center、bottom、left、right | 上、中、下、左、右 |
| 精确单位 | 由浮点数加上单位标识符组成 | 比如20px |
注意点如下:
x、y坐标都是方位名词时,两个值的前后顺序无关,比如top center和center top的效果一样;background-position只有一个取值为方位名词,则默认另一个值为居中对齐;x的坐标,此时y坐标默认居中对齐;background-position取值是方位名词和精确单位混合使用时,则第一个值表示x坐标,第二个值表示y坐标
<head>
<style>
div {
width: auto;
height: 800px;
background-color: bisque;
background-image: url(images.png);
background-repeat: no-repeat;
background-position: top right;
}
style>
head>
<body>
<div>
这里是一段文字
div>
html>
效果如下:

在上述代码中,可以看到背景设置的代码量较多。为了简化背景属性的代码量,我们可以将这些属性合并简写在同一个属性background中,从而节约代码量。
当使用简写属性background时,约定顺序如下:
background: 颜色 图片地址 是否平铺 滚动效果 图片位置
这也是开发中提倡的写法。
举个例子:
div {
background-color: red;
background-image: url(images.png);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: top right;
}
上述代码可以简写为:
div {
background: red url(images.png) no-repeat fixed top right;
}
总结的说,使用简写属性background时,属性值的顺序为:
background-colorbackground-imagebackground-repeatbackground-attachmentbackground-position备注:属性值不写全,缺失一两项也可以,顺序别换就行。
CSS为我们提供背景颜色透明的效果。语法如下:
background: rgba(0, 0, 0, 0.3);
备注:
alpha透明度,取值在0~1之间,其指定了颜色的不透明度;0.3的0省略掉,直接写成:background: rgba(0, 0, 0, .3);效果举例:

| 背景属性 | 值 | 含义 |
|---|---|---|
background-color | 颜色名称 / 十六进制 / RGB代码 | 背景颜色 |
background-image | url( 图片地址 ) | 背景图片 |
background-repeat | repeat / no-repeat / repeat-x / repeat-y | 背景平铺 |
background-attachment | scroll / fixed | 背景附着 |
background-position | 方位名词 / 精确单位 | 背景位置 |
好了,本篇笔记就到写这,欢迎大家到评论区一起讨论!