目录
一、CSS背景概述
CSS 背景属性用于定义HTML元素的背景。
CSS 背景属性:
- background-color
- background-image
- background-repeat
- background-attachment
- background-position
下面我们依次来学习!!!
二、background-color
background-color 属性定义了元素的背景颜色.
CSS中,颜色值通常以以下方式定义:
- 十六进制 - 如:"#ff0000"
- RGB - 如:"rgb(255,0,0)"
- 颜色名称 - 如:"blue"
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>背景颜色</title>
<style>
h1
{
background-color:#6495ed;
}
p
{
background-color:#e0ffff;
}
div
{
background-color:#b0c4de;
}
</style>
</head>
<body>
<h1>CSS background-color 实例!</h1>
<div>
该文本插入在 div 元素中。
<p>该段落有自己的背景颜色。</p>
我们仍然在同一个 div 中。
</div>
</body>
</html>
运行结果:
三、background-image
background-image属性指定用作元素背景的图像
默认情况下,图像会重复,以覆盖整个元素
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>背景图</title>
<style>
body
{
background-image:url('http://static.runoob.com/images/mix/paper.gif');
background-color:#cccccc;
}
</style>
</head>
<body>
<h1>Nice to meet you!</h1>
</body>
</html>
运行结果:
四、background-repeat
默认情况下,background-repeat属性在水平和垂直方向上都重复图像
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-image: url("/i/css/gradient_bg.png");
background-repeat: repeat-x;
}
</style>
</head>
<body>
<h1>Hello World!</h1>
<p>背景图像仅在水平方向上重复!</p>
</body>
</html>
运行结果:
五、background-attachment
background-attachment属性指定背景图像是应该滚动还是固定的(不会随页面的其余部分一起滚动)
- 滚动:background-attachment: scroll
- 固定:background-attachment: fixed
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-image: url("/i/photo/tree.png");
background-repeat: no-repeat;
background-position: right top;
margin-right: 200px;
background-attachment: fixed;
}
</style>
</head>
<body>
<h1>background-attachment 属性</h1>
<p>背景图像是固定的。请尝试向下滚动页面。</p>
...
<p>背景图像是固定的。请尝试向下滚动页面。</p>
</body>
</html>
固定运行结果:
滚动运行结果:
六、background-position
在以上实例中我们可以看到页面的背景颜色通过了很多的属性来控制,为了简化这些属性的代码,我们可以将这些属性合并在同一个属性中
使用简写属性在一条声明中设置背景属性:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background: #ffffff url("/i/photo/tree.png") no-repeat right top;
margin-right: 200px;
}
</style>
</head>
<body>
<h1>background 属性</h1>
<p>background 属性是在一条声明中指定所有背景属性的简写属性。</p>
</body>
</html>
运行结果: