通过CSS背景属性,可以给页面元素添加背景样式。
背景属性可以设置背景颜色、背景图片、背景平铺、背景图片位置、背景图像固定等。
background-color属性定义了元素的背景颜色。
background-color: 颜色值|transparent(透明);
一般情况下元素背景颜色默认值是transparent(透明),也可以手动指定背景颜色为透明色。
代码示例:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS背景之背景颜色title>
<style>
div {
width: 300px;
height: 200px;
/* background-color: transparent; 透明的,清澈的 */
background-color: steelblue;
}
style>
head>
<body>
<div>
div>
body>
html>

background-image属性描述了元素的背景图像。实际开发中常见于logo或者一些装饰性的小图片或者是超大的背景图片,优点是非常便于控制位置(精灵图也是一种运用场景)
background-image: none|url (url)
| 参数值 | 作用 |
|---|---|
| none | 无背景图(默认的) |
| url(url) | 使用绝对或相对地址指定背景图像 |
代码示例:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS背景之背景图片title>
<style>
div {
width: 500px;
height: 600px;
/* 不要落下 url(url) */
background-image: url(images/baidu_logo.png);
}
style>
head>
<body>
<div>div>
body>
html>

background-repeat属性使背景图片在HTML页面上进行平铺。
background-repeat: repeat | no-repeat | repeat-x | repeat-y
| 参数值 | 作用 |
|---|---|
| repeat | 背景图像在纵向和横向上平铺(默认) |
| no-repeat | 背景图像不平铺 |
| repeat-x | 背景图像在横向上平铺 |
| repeat-y | 背景图像在纵向平铺 |
代码示例:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS背景之背景图片、背景平铺title>
<style>
div {
width: 900px;
height: 6800px;
/* 不要落下 url(url) */
background-image: url(images/baidu_logo.png);
/* 背景图片不平铺 */
/* background-repeat: no-repeat; */
/* 默认情况下图片是平铺的 */
/* background-repeat: repeat; */
/* 沿着x轴平铺 */
/* background-repeat: repeat-x; */
/* 沿着y轴平铺 */
background-repeat: repeat-y;
/* 页面元素既可以添加背景颜色也可以添加背景图片 只不过背景图片会压住背景颜色 */
background-color: steelblue;
}
style>
head>
<body>
<div>div>
body>
html>
