原文来自http://bitsofco.de/styling-broken-images/
翻译工做有本人担任,转载请注明出处。html
但它们不是必须这样,咱们能够使用CSS去修饰<img>,由此对加载失败的图片赋予好看的样式。前端
为了理解咱们怎样装饰加载失败的图片,咱们须要先了解两个关于<img>元素的行为表现。
咱们能够给img添加字体样式,那些样式会被施加到alt属性中的替代文字里。若是图片正常显示,那么文字将不会出现。浏览器
<img>元素是一个替换元素(样式和尺寸会被外部资源替代)。由于图片会被替代,那么<img>上的:before和:after这样的伪元素就不会成功显示,可是若是图片未加载成功,那么这些伪元素就会显示出来。微信
由于这些特性,咱们能够给那些未成功加载的<img>元素添加一些样式,当图未加载成功的时候,样式能够显现;若是加载成功,对图片也不会有影响。字体
用咱们知道的两条特性,咱们作了一些例子来装饰未加载的图片。优化
<img src="http://bitsofco.de/broken.jpg" alt="Kanye Laughing">
咱们能够经过使用attr( )来优化未成功加载的图片的显示。url
img { font-family: 'Helvetica'; font-weight: 300; line-height: 2; text-align: center; width: 100%; height: auto; display: block; position: relative; } img:before { content: "We're sorry, the image below is broken :("; display: block; margin-bottom: 10px; } img:after { content: "(url: " attr(src) ")"; display: block; font-size: 12px; }
咱们能够经过伪元素去替代alt文字,经过定位伪元素,使它覆盖在alt文字上。spa
img { /* Same as first example */ } img:after { content: "\f1c5" " " attr(alt); font-size: 16px; font-family: FontAwesome; color: rgb(100, 100, 100); display: block; position: absolute; z-index: 2; top: 0; left: 0; width: 100%; height: 100%; background-color: #fff; }
经过替代一些本地信息,咱们能够使用伪元素更好地修饰未成功加载的图片翻译
img { /* Same as first example */ min-height: 50px; } img:before { content: " "; display: block; position: absolute; top: -10px; left: 0; height: calc(100% + 10px); width: 100%; background-color: rgb(230, 230, 230); border: 2px dotted rgb(200, 200, 200); border-radius: 5px; } img:after { content: "\f127" " Broken Image of " attr(alt); display: block; font-size: 16px; font-style: normal; font-family: FontAwesome; color: rgb(100, 100, 100); position: absolute; top: 5px; left: 0; width: 100%; text-align: center; }
遗憾的是,有一些浏览器仍是没法兼容这样的问题。虽然有些浏览器当图片未加载成功是没法正常显示伪元素的内容,可是这并不影响咱们使用。小伙伴们快尝试起来吧!3d
如对个人文章感兴趣,请关注微信公众号“每日前端”,天天分享一篇优质前端文章。