文章目录
背景样式
background-color 背景颜色
background-color属性可以设置值为:
- 颜色编号(RGB)
- 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>Document</title>
<style>
div {
background-color: transparent;
}
p {
background-color: red;
}
</style>
</head>
<body>
<div>设置透明背景</div>
<p>设置红色背景</p>
</body>
</html>
显示效果为:
background-image 背景图片
插入背景图片比直接插入图片更容易控制位置,适用于logo 或者一些装饰性的小照片或者是超大的背景图片,配合 background-repeat 以及 background-position 属性来使用。
background-image的属性值可以设置为:
- none 不设置背景图片
- 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>Document</title>
<style>
div {
width: 500px;
height: 500px;
background-image: url(../img/img.jpg);
}
</style>
</head>
<body>
<div></div>
</body>
</html>
背景照片会默认平铺在你设置的范围内:
background-repeat 背景平铺
- repeat 图象在纵向和横向上平铺
- no-repeat 图象不平铺
- repeat-x 背景图象在横向上平铺
- repeat-y 背景图象在纵向上平铺
如果想要沿着x轴平铺
<!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>Document</title>
<style>
div {
width: 500px;
height: 500px;
background-image: url(img.jpg);
background-repeat: repeat-x;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
效果如下:
background-position 背景图片位置
background-position 属性值是x和y,x和y可以由 方位名词 和 精确单位 来表示
- 如果参数是方位名词,则xy的前后顺序无影响,方位名词有:
- center 和 top
- right 和 left
- 如果参数是精确单位,那两个参数的位置就不能改变,如
background-position: 50px 60px;
x轴一定是50px,y轴一定是60px
<!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>Document</title>
<style>
div {
width: 500px;
height: 500px;
background-image: url(../img/img.jpg);
background-repeat: no-repeat;
background-position: 50px 50px;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
效果大致如下:
- 如果参数是精确单位和方位名词混合使用,则第一个值是x坐标,第二个值是y坐标
background-attachment 背景附着
属性值有两个
- scroll 背景图像随着对象内容滚动
- fixed 背景图象固定
复合写法
没有特定的书写顺序,一般约定为:
background: 背景颜色 背景图片地址 背景平铺 背景图象滚动 背景图片位置
background: rgba() 设置背景半透明
background: rgba()中有四个参数:
- 前三个参数用于设置颜色
- 最后一个参数用于设置透明度,取值范围为0-1,越大越不透明
<!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>Document</title>
<style>
div {
color: white;
background: rgba(0,0,0);
}
p {
color: wheat;
background: rgba(0, 0, 0, 0.5)
}
</style>
</head>
<body>
<div>设置黑色背景</div>
<p>设置半透明的黑色背景背景</p>
</body>
</html>