[英]Fallback image with CSS
我有一个<img>
显示远程图像。 我希望它回退到另一个本地图像,在远程图像无法访问的情况下。
<img class="cc_image fallback" src="http://www.iconarchive.com/download/i82888/limav/flat-gradient-social/Creative-Commons.ico">
.cc_image {
width: 256px;
height: 256px;
}
.cc_image.fallback {
/* this URL here is theoretically a local one (always reachable) */
background-image: url('https://cdn2.iconfinder.com/data/icons/picons-basic-3/57/basic3-010_creative_commons-256.png');
}
它的工作原理是,当找不到src图像时,将显示背景图像。
缺点是:
我该如何解决这些问题? 或者:还有其他技术可以达到相同的结果吗?
我发现了这个问题,但给定的解决方案依赖于 Javascript 或<object>
(这似乎不适用于 Chrome)。 我想要一个纯 CSS/HTML 解决方案,如果可能的话,不要使用 Javascript。
我知道多个background-image
但不确定它是否是一个好的选择(浏览器支持?它会以无法访问的图像回退吗?)。 或者我正在考虑将 SVG 图像嵌入为data-uri 。
对最灵活(和兼容)方法的建议?
不幸的是,如果没有 Javascript 或 object 标签,您将无法同时实现。
您可以这样做以避免丢失图像图标:
将您的图像放在一个容器中(它可能已经在一个容器中)。 使容器与图像具有相同的宽度和高度。
代码:
HTML
<!-- you could use any other tag, such as span or a instead of div, see css below -->
<div class="cc_image_container fallback">
<img class="cc_image" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" style="background-image: url(*your remote image*)"/>
</div>
CSS
.fallback {
background-image: url(*fallback image here*);
display: inline-block; /*to ensure it wraps correctly around the image, even if it is a a or span tag*/
min-width: specify a minimum width (could be the width of the fallback image) px;
min-height: specify a minimum height (could be the height of the fallback image) px;
background-position: center center; // fallback for older browsers
background-size: cover;
background-repeat: no-repeat;
}
.cc_image {
min-width: same as container px;
min-height: same as container px;
background-position: center center; // fallback for older browsers
background-size: cover;
background-repeat: no-repeat;
}
min-width
和max-width
确保背景图像保持可见。background-position
确保图像的中心部分仍然可见,并且是旧浏览器的优雅降级background-size
调整背景图像的大小以填充元素背景。 cover
值意味着将调整图像大小,使其完全覆盖元素(图像的某些外边缘可能会被裁剪)我在Codepen上找到了一个解决方案,想和大家分享一下: https ://codepen.io/anon/pen/Eqgyyo
我更喜欢这个解决方案,因为它适用于真实的图像标签,而不是背景图像。
body { color: #2c3e50; font-family: 'verdana'; line-height: 1.35em; padding: 30px; } h1 { margin-bottom: 40px; } ul { list-style: none; padding: 0; } * { box-sizing: border-box; } img { color: #95a5a6; font-size: 12px; min-height: 50px; position: relative; } img:before { background: #f1f1f1; border: 1px solid #ccc; border-radius: 3px; content: '\\1F517' ' broken image of 'attr(alt); display: block; left: 0; padding: 10px; position: absolute; top: -10px; width: 100%; }
<h1>Broken image fallback CSS</h1> <img src="no-image-here" alt="Cats with synthesizers in the space " /> <br /><br /> <ul> <li>✓ Firefox</li> <li>✓ Chrome</li> <li>✓ Opera</li> <li>✗ Safari (desktop, mobile)</li> <li>✗ iOS webview</li> </ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.