CSS 背景属性用于定义HTML元素的背景。
CSS 属性定义背景效果:
- background-color
- background-image
- background-repeat
- background-attachment
- background-position
背景:
1.设置背景色:
backgroud-color设置背景色,这个属性接受任何合法的颜色值。
body {background-color:#b0c4de;}
CSS中,颜色值通常以以下方式定义:
- 十六进制 - 如:"#ff0000"
- RGB - 如:“rgb(255,0,0)”
- 颜色名称 - 如:“red”
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
.box1{
width: 200px;
height: 400px;
/* 名称格式设置 */
background-color: red;
/* 十六进制格式设置 */
background-color: #FF0000;
/* rgb格式设置 */
background-color: rgb(100,200,300);
/* rbga可以设置透明度 */
background-color: rgba(100,200,300,0.2);
}
</style>
</head>
<body>
<div class="box1"></div>
</body>
</html>
2.设置背景图片:
background-image:要把图像放入背景,属性的默认值是none,标识背景上没有放置任何图像,如果需要设置一个背景图,必须设置一个URL值
大多数背景图都用在body元素;
背景图平铺:
如果需要在页面上对背景图像进行平铺,可以使用background-repeat属性;
属性值:
- repeat:水平和垂直都平铺
- repeat-x:水平方向
- repeat-y:垂直方向
- no-repeat:不允许平铺
默认的话,背景图从一个元素的左上角开始;
body
{
background-image:url('gradient2.png');
background-repeat:repeat-x;
}
3.背景定位::
以上实例中,背景图像与文本显示在同一个位置,为了让页面排版更加合理,不影响文本的阅读,我们可以改变图像的位置。
可以利用background-position属性改变图像在背景中的位置;
定位方式:位置关键字,百分比;
定义左右的关键字是:left right
上下是:top bottom
body
{
background-image:url('img_tree.png');
background-repeat:no-repeat;
background-position:right top;
}
4.背景- 简写属性
在以上实例中我们可以看到页面的背景颜色通过了很多的属性来控制。
为了简化这些属性的代码,我们可以将这些属性合并在同一个属性中.
背景颜色的简写属性为 “background”:
body {background:red url('img_tree.png') no-repeat right top;}
当使用简写属性时,属性值的顺序为:
- background-color 颜色
- background-image 背景图片
- background-repeat 平铺设置
- background-attachment
- background-position 位置
以上属性无需全部使用,你可以按照页面的实际需要使用.