Skip to content
On this page

图片加载出错样式设置

TIP

冷知识:图片加载出错时,为img元素设置的伪元素::before/::after会生效,图片正常加载时,不会生效

代码展示

html代码

html
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Image Error Display</title>
    <link rel="stylesheet" href="./index.css">
</head>
<body>
    <div class="img-error--handle">
        <div>
            <h1>图片加载出错时的处理</h1>
            <h2>加载出错</h2>
            <img class="img-target" src="./a.png" alt="我是一张风景图画">
            <h2>正确加载</h2>
            <img class="img-target" src="./image/landscape.webp" alt="landscape">
        </div>
    </div>
</body>
</html>

css代码

css
.img-error--handle {
    margin: 100px auto 0;
    display: flex;
    justify-content: center;
}
.img-target {
    width: 200px;
    height: 200px;
    position: relative;
    display: block;
}
.img-target::before {
    content: "";
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    color: transparent;
    background: #F5F5F5 url("./image/image-error.webp") no-repeat center / 50% 50%;
}
.img-target::after {
    content: attr(alt);
    position: absolute;
    width: 100%;
    background-color: rgba(0, 0, 0, .5);
    left: 0;
    bottom: 0;
    line-height: 2;
    color: #FFFFFF;
    font-size: 12px;
    text-align: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    box-sizing: border-box;
    padding: 0 10px;
}

效果预览