CSS实现骨架屏卡片效果

41 阅读2分钟

从别处学来的,站在巨人的肩膀上,一起走的更远吧。

效果图如下:

动画21.gif

直接上代码:

<body>
    <div class="card">
      <div class="image">
        <img src="/1.png" alt="" />
      </div>
      <div class="content">
        <h4>Hello World!</h4>
        <div class="des">
          Don't assume that someone older than you necessarily knows what to do
        </div>
      </div>
    </div>
    <div class="card loading">
      <div class="image"></div>
      <div class="content">
        <h4></h4>
        <div class="des"></div>
      </div>
    </div>
  </body>
<style>
      body {
        margin: 0;
        padding: 0;
        background-color: #f6f6f6;
        font-family: Arial, Helvetica, sans-serif;
        font-size: 15px;
        display: flex;
        justify-content: space-around;
        align-items: center;
        min-height: 100vh;
      }
      .card {
        width: 320px;
        background-color: #fff;
        border-radius: 6px;
        overflow: hidden;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.12);
      }
      .image {
        height: 200px;
      }
      .image img {
        display: block;
        width: 100%;
        height: inherit;
        object-fit: cover;
      }
      .content {
        padding: 2rem 1.8rem;
      }

      h4 {
        margin: 0 0 1rem;
        font-size: 1.5rem;
        line-height: 1.5rem;
      }
      .des {
        font-size: 1rem;
        line-height: 1.4rem;
      }

      .loading .image,
      .loading h4,
      .loading .des {
        /* background-color: #ededed; */
        /* 1、利用背景来设置条形波浪,使用20%的区域显示波浪,其他区域仍然显示背景色 */
        /* 颜色后面的百分比,意思是这个颜色从这个位置开始 */
        background: linear-gradient(
            100deg,
            rgba(255, 255, 255, 0) 40%,
            rgba(255, 255, 255, 0.5) 50%,
            rgba(255, 255, 255, 0) 60%
          )
          #ededed;
        /* 2、使条形波能够移动,即移动背景 */
        /* 先放大背景(宽度放大两倍,高度不变),要不然无法移动 */
        background-size: 200% 100%;
        /* 移动背景图x轴的位置,即可让条纹滚动 */
        /* 先把条纹移动到左侧外面,设置x轴位置为>100% */
        background-position-x: 120%;
        /* 4、使用移动动画 */
        animation: loading 1s ease-in-out infinite;
      }
      /* 3、定义一个动画,让这个条形波浪向右移动 */
      @keyframes loading {
        to {
          background-position-x: -20%;
        }
      }
      /* 5、因为content有一个padding,导致h4和des宽度不是100%,所以条纹不是一条直线,需要给这两个动画加上一个延迟 */
      .loading h4 {
        min-height: 1.6rem;
        border-radius: 4px;
        animation-delay: 0.05s;
      }
      .loading .des {
        min-height: 4rem;
        border-radius: 4px;
        animation-delay: 0.06s;
      }
    </style>

小案例,复习旧知识+学习新知识。总会有收获的。