您当前的位置: 首页 >  css

彭世瑜

暂无认证

  • 3浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

css:利用伪类处理图片加载失败的样式问题

彭世瑜 发布时间:2022-09-30 10:17:33 ,浏览量:3

实现效果 在这里插入图片描述

实现代码

index.html

    未做错误处理
     
      

      
    

    有错误处理
    
      
      
    

style.css

img {
  width: 300px;
  height: 150px;
  object-fit: cover;
  display: inline-block;
}

.mo-image {
  display: inline-block;
  /* transform: scale(1); */
  position: relative;
}

/* 显示占位图片 */
.mo-image::before {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: #f5f5f5 url(../img/image-error.jpg) no-repeat center / 50% 50%;
  color: transparent;
}

/* 显示alt中的文字 */
.mo-image::after {
  content: attr(alt);
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  line-height: 2;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  font-size: 12px;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

在线示例:https://mouday.github.io/front-end-demo/image-error/index.html

参考 视频:图片加载出错样式最佳实践

关注
打赏
1665367115
查看更多评论
立即登录/注册

微信扫码登录

0.0573s