Wscats / articles

🔖My Learning Notes and Memories - 分享我的学习片段和与你的回忆

Home Page:https://github.com/Wscats/articles

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

CSS图片响应式布局

Wscats opened this issue · comments

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Wsscat DEMO</title>
    </head>

    <body>
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
    </body>
    <style>
        body {
            margin: 0;
            padding: 0;
        }

        .box {
            float: left;
            width: 30%;
            margin-top: 10px;
            margin-left: 2.5%;
            height: 0;
            padding-bottom: 33.98%;
            background-color: #dbe0e4;
            background-image: url(29381f30e924b899de6cd36f68061d950a7bf611.jpg);
            background-size: cover;
        }
    </style>
</html>

这是后面要展示在图片盒里面的图片素材,可以看到这张素材不是1:1的比例的,但是在后面展示的时候不会将它进行缩放
29381f30e924b899de6cd36f68061d950a7bf611
效果如下,可以看到在移动端的效果
image
以前我在做这种响应式布局的时候经常要用到JS来计算盒子变动后的长宽,其实实现这种效果只要用到CSS就可以了,实现这种方法的关键在于利用padding-bottom,当我们用background-image的时候这部分图片就可以展现在padding区域,此时注意height属性,高度是0的,所以这里其实是被padding占了这个区域,并且显示在内边距上,内边距又会根据百分比实现响应
padding-bottom: 33.98%;
image
这里还有一点注意的是,图片我们不要用标签,用这两个属性配合会更好控制图片缩放

background-image: url();
background-size: cover;