【问题标题】:Displaying Loading Image using CSS使用 CSS 显示加载图像
【发布时间】:2020-07-11 03:32:07
【问题描述】:

我目前将以下 CSS 代码应用于显示响应式图像的 div 元素。

.my-img-container {
  position: relative;
  &:before {
    display: block;
    content: " ";
    background: url("https://lorempixel.com/300/160/") no-repeat;
    background-size: 100% 100%;
    width: 100% !important;
    padding-top: 56.25%;
  }
  >img {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100% !important;
    height: 100% !important;
  }
}
<div class="my-img-container">
  <img srcset="https://lorempixel.com/540/304 540w, https://lorempixel.com/960/540 960w" sizes="(min-width: 576px) 540px, 100vw" src="https://lorempixel.com/300/160">
</div>

我想要做的是在加载响应图像时在背景中显示图像,因此 CSS 中的 content,但它不起作用。知道为什么吗?

【问题讨论】:

    标签: html css pseudo-class responsive-images


    【解决方案1】:

    与其加载较小的图像以显示为 loader,不如简单地旋转一个伪元素。

    它的好处是能够比图像更快地启动并节省额外的服务器调用。

    .my-img-container {
      position: relative;
      padding-top: 50%;
    }
    .my-img-container:before {
      content: " ";
      position: absolute;
      top: 50%;
      left: 50%;
      width: 80px;
      height: 80px;
      border: 2px solid red;
      border-color: transparent red transparent red;
      border-radius: 50%;
      animation: loader 1s linear infinite;
    }
    .my-img-container > img {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      width: 100% !important;
      height: 100% !important;
    }
    @keyframes loader {
      0% {
        transform: translate(-50%,-50%) rotate(0deg);
      }
      100% {
        transform: translate(-50%,-50%) rotate(360deg);
      }
    }
    <div class="my-img-container">
      <img src="https://picsum.photos/600/300">
    </div>

    【讨论】:

      【解决方案2】:

      您可以将微调器设置为图像的背景:

      html,
      body {
        height: 100%;
        margin: 0;
      }
      
      img {
        display: block;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        width: 100%;
        height: 100%;
        background: url(https://upload.wikimedia.org/wikipedia/commons/b/b1/Loading_icon.gif) no-repeat center;
      }
      &lt;img srcset="https://picsum.photos/540/304 540w, https://picsum.photos/960/540 960w" sizes="(min-width: 576px) 540px, 100vw" src="https://picsum.photos/300/160"&gt;

      【讨论】:

      • 当我们使用object-fit: contain时会很奇怪
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-05
      • 1970-01-01
      • 1970-01-01
      • 2014-10-19
      • 1970-01-01
      • 2016-12-28
      • 1970-01-01
      相关资源
      最近更新 更多