背景尺寸
background-size 的单位可以是px,也可以是百分比,当尺寸为百分比的时候,相对于所在元素。 background-image可以置顶多张背景图
属性演示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS3背景</title>
<style>
#test{
width: 200px;
height: 170px;
background-image: url("images/test.jpg");
background-size: 100% 100%;
}
</style>
</head>
<body>
<div id="test"></div>
</body>
</html>

多张背景:
使用多张背景时,图片层级堆叠,如果上层图片不是半透明或者存在透明像素,下层图片就不会显示出来
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS3背景</title>
<style>
#test{
width: 200px;
height: 170px;
background-image: url("images/1.png"),url("images/test.jpg");
background-size: 100% 100%;
}
</style>
</head>
<body>
<div id="test"></div>
</body>
</html>

background-origin
限制背景图片的范围,有三个范围:content-box、padding-box 或 border-box 区域

content-box:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS3背景</title>
<style>
#test{
border: #4361ee 2px solid; /*设置边框,便于观察*/
width: 200px;
height: 170px;
padding:35px;/*设置padding,把三个区域区分开*/
background-origin: content-box;
background-image: url("images/1.png"),url("images/test.jpg");
background-repeat: no-repeat;/*背景不重复,便于观察,背景设置成重复,background-origin属性无法很好的体现*/
background-size: 100% 100%;
}
</style>
</head>
<body>
<div id="test">Hello</div>
</body>
</html>

padding-box:
<style>
#test{
border: #4361ee 12px solid; /*增加了边框宽度,便于观察*/
width: 200px;
height: 170px;
padding:35px;/*设置padding,把三个区域区分开*/
background-origin: padding-box;/* 改成了padding-box */
background-image: url("images/1.png"),url("images/test.jpg");
background-repeat: no-repeat;/*背景不重复,便于观察,背景设置成重复,background-origin属性无法很好的体现*/
background-size: 100% 100%;
}
</style>

border-box:
<style>
#test{
border: transparent 12px solid; /*设置边框为透明色,放置遮挡背景图像,便于观察*/
width: 200px;
height: 170px;
padding:35px;/*设置padding,把三个区域区分开*/
background-origin: border-box;/*改成了border-box*/
background-image: url("images/1.png"),url("images/test.jpg");
background-repeat: no-repeat;/*背景不重复,便于观察,背景设置成重复,background-origin属性无法很好的体现*/
background-size: 100% 100%;
}
</style>

background-clip
设置裁剪背景图,有三个区域,和background-origin区域相同
演示裁剪到content-box
<style>
#test{
border: #4361ee 12px solid;
width: 200px;
height: 170px;
padding:35px;
background-clip: content-box;
background-image: url("images/1.png"),url("images/test.jpg");
background-repeat: no-repeat;
background-size: 100% 100%;
}
</style>

本文深入解析CSS3中背景属性的使用技巧,包括background-size、background-image、background-origin及background-clip等关键属性,通过实例展示如何设置背景尺寸、多背景图层叠及背景裁剪效果。
143

被折叠的 条评论
为什么被折叠?



