背景尺寸属性是用来修改背景图片大小的属性。
格式为:
background-size:宽度 高度;
取值:
1、具体像素;
background-size:100px 100px;设置背景图片宽度与高度均为100px。
2、百分比;
background-size:50% 100%;设置设置背景图片宽度为当前元素宽度的一半,高度为当前元素的高度。
3、等比拉伸;
要想实现等比拉伸,需要使用auto属性,宽度等比拉伸时,将宽度设为auto,高度等比拉伸时,高度设为auto。
background-size:50px auto;
4、cover;
cover属性是将图片宽度高度同时等比拉伸,直到图片完全覆盖到当前元素。
5、contain;
contain属性也是等比拉伸,但与cover相比,contain将图片拉伸时,当宽度或者高度为当前元素宽高时,便停止;而 cover会继续拉伸,直到完全铺满当前元素。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style>
* {
margin: 0;
padding: 0;
}
ul li {
list-style: none;
width: 200px;
height: 200px;
border: 1px solid #000;
float: left;
line-height: 200px;
text-align: center;
margin: 10px;
color: red;
}
ul li:nth-child(1) {
background: url("1.jpg") no-repeat;
}
ul li:nth-child(2) {
background: url("1.jpg") no-repeat;
background-size: 100px 100px;
}
ul li:nth-child(3) {
background: url("1.jpg") no-repeat;
background-size: 50% 100%;
}
ul li:nth-child(4) {
background: url("1.jpg") no-repeat;
background-size: auto 75%;
}
ul li:nth-child(5) {
background: url("1.jpg") no-repeat;
background-size: 50% auto;
}
ul li:nth-child(6) {
background: url("1.jpg") no-repeat;
background-size: cover;
}
ul li:nth-child(7) {
background: url("1.jpg") no-repeat;
background-size: contain;
}
</style>
<body>
<ul>
<li>默认</li>
<li>具体像素</li>
<li>百分比</li>
<li>宽度等比拉伸</li>
<li>高度等比拉伸</li>
<li>cover</li>
<li>contain</li>
</ul>
</body>
</html>