zoukankan      html  css  js  c++  java
  • css使用padding-bottom百分比进行提前占位,防止抖动

    页面加载抖动问题

    在web开发中,经常会遇到这样一个问题,比如一个宽度百分百,高度自适应的图片,在网速慢的情况下加载过程中会出现抖动的问题(未加载图片前容器的高度为0,图片加载完成后下面的内容会被挤下去)。

    这种问题如果是图片有固定高度,就不会出现加载抖动。但一般情况下,为了使图片不被拉伸,高度一般设为自适应,那么为了防止加载抖动,我们需要给图片提前占个位,这里使用的是css的padding-bottom百分比进行占位。

    示例代码如下

    .img-box{
      overflow: hidden;
       100%;
      height: 0;
      padding-bottom: 50%;
    }
    

    padding-bottom实际上是提前占位了,这个容器的高度始终是0,高度为0还之所以能够显示内容是因为内容溢出在了padding-bottom上,这里的50%是图片的高宽比例,切记是相对于父元素宽度的50%(即.img-box的上一级),不是相对于自己的width,详情请看下面的例子。

    这里写了一个小案例

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8">
      <title>padding-bottom</title>
      <style>
        .content{
           400px;
          height: 400px;
          margin: 100px auto;
          background-color: aquamarine;
        }
        .box1{
           100%;  /* 400px 相对于content的width */
          height: 0;
          padding-bottom: 50%;  /* 200px 相对于content的width */
          background-color: red;
        }
        .box2{
           25%; /* 100px 相对于box1的width */
          height: 0;
          padding-bottom: 25%;  /* 100px 相对于box1的width */
          background-color: yellow;
        }
      </style>
    </head>
    <body>
      <div class="content">
        <div class="box1">
          <div class="box2"></div>
        </div>
      </div>
    </body>
    </html>
    

    如图所示

    padding-bottom

    这种情况下box2中如果有图片宽高比为一比一时(根据padding的百分比),加载过程中就不会出现抖动的情况,同理box1也是如此。

    当然解决抖动还有其他方法,比如何以用vw(兼容性不太好,这里就不列举了),还有比如在微信小程序中rpx,如果图片的设计大小宽高为750×300时,就可以直接写成height: 300rpx。

    完结~
  • 相关阅读:
    正则表达式
    Ajax跨域问题---jsonp
    Ajax
    字符串总结
    js 字符串加密
    jsDate()
    HDU 5430 Reflect
    HDU 5429 Geometric Progression
    HDU 5428 The Factor
    POJ 2485 Highways
  • 原文地址:https://www.cnblogs.com/lwlblog/p/12304879.html
Copyright © 2011-2022 走看看