Skip to main content

最佳实践

图片加载失败时

img特性:图片正常加载时,伪元素会失效;但如果加载失败,伪元素会生效

占位符

  • HTML
<img src="url.png" alt="CSS处理加载失败占位符" />
  • CSS
img {
display: inline-block;
transform: scale(1);
}

img::before {
content: '';
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: #f5f5f5 url(break.svg) no-repeat center / 50% 50%;
color: transparent;
}

img::after {
content: attr(alt);
position: absolute;
left: 0;
bottom: 0;
width: 100%;
line-height: 2;
background: rgba(0, 0, 0, .5);
color: #fff;
font-size: 14px;
text-align: center;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}

没头像时使用名字的首字母

  • CSS
img.avatar {
display: inline-block;
--s: var(--size,1.5rem);
width: var(--s);
height: var(--s);
border-radius: 50%;
white-space: normal;
overflow: hidden;
}

img.avatar::before {
content: attr(alt);
display: flex;
font-size: calc(var(--s)*.5);
width: 100%;
height: 100%;
background-color: bisque;
line-height: var(--s);
letter-spacing: var(--s);
text-indent: var(--s);
justify-content: center;
text-align: center;
color: inherit;
line-break: anywhere;
}