2025年4月16日 星期三 乙巳(蛇)年 正月十七 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Html+Div+Css(前端)

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

时间:05-29来源:作者:点击数:30

实现效果

在这里插入图片描述

实现代码

index.html

  • <h2>未做错误处理</h2>
  • <div style="font-size: 0">
  • <img src="./img/image.jpg" alt="" />
  • <img src="./img/image-1.jpg" alt="" />
  • </div>
  • <h2>有错误处理</h2>
  • <div style="margin-top: 20px; font-size: 0; display: flex">
  • <img class="mo-image" src="./img/image.jpg" alt="标题" />
  • <img class="mo-image" src="./img/image-1.jpg" alt="标题" />
  • </div>

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

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门