移动端padding和margin的百分比设置实现占位

资源请求和加载都是需要时间的。对于图片一些内容的展示,当图片没有加载出来时。容器高为零,那么下面的dom元素会上移。当图片加载后,会容器撑开。这样会造成页面的重排。

为了解决以上问题我们可以使用padding的百分比占位实现(或者margin)。

让我们把padding这是为百分比时。他百分比对应的是父级的宽的比(W3C规定)

我们就实现了占位。我们需要占位的空间添加内容,这时我们就需要定位属性或者浮动来解决(当父级高度设置为0的时候有惊喜)

* {
    margin: 0;
    padding: 0;
    list-style: none;
}
.wrapper {
    /* 弹性盒子。换行处理。内容居中 */
    display: flex; 
    flex-wrap: wrap;
    justify-content: center;
}
.box {
    position: relative;
    width: 25%;
    padding-bottom: 25%;
    background-color: #eee;
    float: left;
    /* background-color: green; */
    margin-left: 10px;
    margin-bottom: 10px;
}
.box img{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

CSS基本样式,我们可以用定时器模拟图片的加载过程。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            list-style: none;
        }

        .wrapper {
            /* 弹性盒子。换行处理。内容居中 */
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
        }

        .box {
            position: relative;
            width: 25%;
            padding-bottom: 25%;
            background-color: #eee;
            float: left;
            /* background-color: green; */
            margin-left: 10px;
            margin-bottom: 10px;
        }

        .box img {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
        }
    </style>
</head>

<body>

    <div class="wrapper">
        <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>

    <script>
        let box = document.getElementsByClassName('box');
        let imgArr = [0, 1, 2, 3, 4, 5, 6, 7, 8];
        let index = 0;
        let timer = setInterval(() => {
            let img = `<img src="./images/${index}.jpg" />`
            box[index].innerHTML = img;
            index++;
            if (index == imgArr.length) {
                clearInterval(timer)
            }
        }, 1000)


    </script>
</body>

</html>

文章有点老~不过利于理解

https://segmentfault.com/a/1190000004231995

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值