背景尺寸

351 阅读1分钟

背景尺寸

background-size属性用来设置背景图片的尺寸,css3新增属性 兼容到IE9;

background-size:10px (宽度) 10px (高度);

参数值也可以是百分数来设置,表示为盒子宽高的百分之多少;

需要等比例设置的值,书写auto;

contain和cover属性值

contain和cover是两个特殊的background-size的值;

contain表示将背景图片智能改变尺寸以容纳到盒子里 ,简言之:就是通过对图片放大缩小使用户可以完整的看到图片,如果设置no-repeat可能会看到空白部分;

cover 表示将背景图片智能改变尺寸以撑满盒子,简言之:就是通过放大,使一张图片不通过repeat就能撑满整个盒子,不让用户看到空白部分;

案例演示


<!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>
        .box1 {
            width:600px;
            height:400px;
            border:1px solid #000;
            background-image:url("logo.png");
            background-size:600px auto;
            margin-bottom:20px;
        }
        .box2 {
            width:600px;
            height:400px;
            border:1px solid #000;
            background-image:url("logo.png");
            background-size:50% auto;
            margin-bottom:20px;
        }
        .box3 {
            width:600px;
            height:400px;
            border:1px solid #000;
            background-image:url("logo.png");
            background-size:25% auto;
            margin-bottom:20px;
        }
        .box4 {
            width:600px;
            height:400px;
            border:1px solid #000;
            background-image:url("logo.png");
            background-size:contain;
            background-repeat:no-repeat;
            margin-bottom:20px;
        }
        .box5 {
            width:600px;
            height:400px;
            border:1px solid #000;
            background-image:url("logo.png");
            background-size:cover;
            background-repeat:no-repeat;
        }
    </style>
</head>
<body>
    <div class="box1"></div>
    <div class="box2"></div>
    <div class="box3"></div>
    <div class="box4"></div>
    <div class="box5"></div>
</body>
</html>