文章目录
CSS 多重背景
向一个元素添加多个背景图像相关属性:
background-size
background-origin
background-clip
CSS 多重背景
CSS 允许您通过 background-image 属性为元素添加多个背景图像。
不同的背景图像用逗号分隔,图像堆叠在一起,其中第一个图像最靠近查看器。
以下示例有两个背景图像,第一个图像是一朵花(与底部和右侧对齐),第二个图像是纸张背景(与左上角对齐):
示例
#example1 {
background-image: url(img_flwr.gif), url(paper.gif);
background-position: 右下,左上;
background-repeat: no-repeat, repeat;
}
可以使用单个背景属性(如上)或背景简写属性指定多个背景图像。
以下示例使用背景简写属性(结果与上例相同):
示例
#example1 {
background: url(img_flwr.gif) right bottom no-repeat, url(paper.gif) left top repeat;
}
CSS 背景大小
CSS background-size 属性允许您指定背景图像的大小。
大小可以用长度、百分比或使用以下两个关键字之一来指定:contain 或 cover。
以下示例将背景图像的大小调整为比原始图像小得多(使用像素):
代码如下:
示例
#div1 {
background: url(img_flower.jpg);
background-size: 100px 80px;
background-repeat: no-repeat;
}
background-size 的另外两个可能值是 contain 和 cover。
contain 关键字将背景图像缩放到尽可能大(但其宽度和高度都必须适合内容区域)。因此,根据背景图像和背景定位区域的比例,背景中的某些区域可能未被背景图像覆盖。
cover 关键字缩放背景图像,使内容区域完全被背景图像覆盖(其宽度和高度等于或超过内容区域)。因此,背景图像的某些部分可能在背景定位区域中不可见。
以下示例说明了 contain 和 cover 的用法:
示例
#div1 {
background: url(img_flower.jpg);
background-size: contain;
background-repeat: no-repeat;
}
#div2 {
background: url(img_flower.jpg);
background-size: cover;
background-repeat: no-repeat;
}
定义多个背景图像的大小
使用多个背景时,background-size 属性还接受多个背景大小值(使用逗号分隔的列表)。
以下示例指定了三幅背景图像,每幅图像的 background-size 值不同:
示例
#example1 {
background: url(img_tree.gif) left top no-repeat, url(img_flwr.gif) right bottom no-repeat, url(paper.gif) left top repeat;
background-size: 50px, 130px, auto;
}
全尺寸背景图像
现在我们想要在网站上有一个始终覆盖整个浏览器窗口的背景图像。
要求如下:
用图像填充整个页面(无空白)
根据需要缩放图像
将图像置于页面中央
不会引起滚动条
以下示例显示了如何执行此操作;使用 <html>
元素(<html>
元素始终至少为浏览器窗口的高度)。然后在其上设置固定且居中的背景。然后使用 background-size 属性调整其大小:
示例
html {
background: url(img_man.jpg) no-repeat center fixed;
background-size: cover;
}
英雄图像
您还可以在 <div>
上使用不同的背景属性来创建英雄图像(带有文本的大图像),并将其放置在您想要的位置。
示例
.hero-image {
background: url(img_man.jpg) no-repeat center;
background-size: cover;
height: 500px;
position:relative;
}
CSS background-origin 属性
CSS background-origin 属性指定背景图像的位置。
该属性有三个不同的值:
border-box - 背景图像从边框的左上角开始
padding-box - (默认)背景图像从填充边缘的左上角开始
content-box - 背景图像从内容的左上角开始
以下示例说明了 background-origin 属性:
示例
#example1 {
border: 10px solid black;
padding: 35px;
background: url(img_flwr.gif);
background-repeat: no-repeat;
background-origin: content-box;
}
CSS background-clip 属性
CSS background-clip 属性指定背景的绘制区域。
该属性有三个不同的值:
border-box -(默认)背景绘制在边框的外边缘
padding-box - 背景绘制在填充的外边缘
content-box - 背景绘制在内容框内
以下示例说明了 background-clip 属性:
示例
#example1 {
border: 10px dotted black;
padding: 35px;
background: yellow;
background-clip: content-box;
}
总结
本文介绍了CSS 多重背景的使用,如有问题欢迎私信和评论