css背景属性有很多,了解这些属性就可以更加灵活的设置背景了。
bg.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>背景测试</title>
<link rel="stylesheet" href="bg.css">
</head>
<body>
</body>
</html>
bg.css
body{
width: 100%;
height: 100%;
overflow: hidden;
}
用一个简单的列子,了解一下
background-image
设置背景图
原图
body{
background-image: url(bg-index.jpg);
}
如果所示,背景图被设置到了网页中
背景还可以指定渐变
body{
background-image: linear-gradient(to right,#583,#fff);
}
还可以指定多个背景,背景直接可以叠加,背景遵循先到先得,先设置的背景在上,这样如果第一张是部分透明的,那么两张就会混合显示,可以实现一些意向不到的功能。
background-position
指定背景的位置,可以设置百分比或者像素,这里设置1000px 10px,背景的位置从图片的左上角1000px 10px开始计算背景的起始位置
body{
background-image: url(bg-index.jpg);
background-position: 1000px 10px;
}
background-size
指定图片的背景大小,指定length或者百分比,还有两个特殊值
cover 保持图像的比例,按照覆盖的最小大小
contain 保持图像的比例,按照覆盖的最大大小
body{
background-image: url(bg-index.jpg);
background-size: 400px 400px;
}
background-repeat
指定背景图片的重复方式,如上图所示,当图片不足以支撑全被容器,就会自动重复铺满整个容器
repeat-y 只在纵向重复
repeat-x 只在横向重复
repeat 横向和纵向都重复
body{
background-image: url(bg-index.jpg);
background-size: 400px 400px;
background-repeat: no-repeat;
}
background-color
设置背景颜色,同时设置背景颜色和背景图片的话,背景颜色会被背景图片覆盖
body{
background-color: #0090C9;
}
background-origin
相对于内容框来定位背景图像
padding-box 默认
border-box
content-box
<div class="org">
</div>
.org{
width: 400px;
height: 400px;
padding: 100px;
box-sizing: border-box;
border: 1px solid #000000;
background-image: url(bg-index.jpg);
background-origin: content-box;
background-repeat: no-repeat;
}
如上图所示将background-origin设置为content-box,背景的起点定位就为content-box。
background-clip
背景裁剪,限制背景的范围,background-origin只是限制了背景的起始位置,不能完全限制背景的范围,和background-origin它也有三个值
padding-box 默认
border-box
content-box
.org{
width: 400px;
height: 400px;
padding: 100px;
box-sizing: border-box;
border: 1px solid #000000;
background-image: url(bg-index.jpg);
background-clip: content-box;
background-repeat: no-repeat;
}
background-attachment
设置背景图像是否固定或者随着页面的其余部分滚动。
scroll 默认的,随着页面滚动而滚动
fixed 固定的,不滚动
local 随着内容滚动