当你准备写一个logo的时候,第一反正是Img还是div?
之前写都是在混乱用,临时想到用哪个就用哪个,但是用哪种是正确的呢?让我们先看看SO上面这个问题的讨论:html - When to use IMG vs. CSS background-image?
下面是支持最多的答案(带翻译):
Proper uses of IMG //img的合适使用
- Use IMG if you intend to have people print your page and you want the image to be included by default. —JayTee
- 使用img:如果你想让人打印你的页面时该图片是被默认包含的
- Use IMG (with alt text) when the image has an important semantic meaning, such as a warning icon. This ensures that the meaning of the image can be communicated in all user-agents, including screen readers.
- 使用img(伴随alt文本):当图片具有重要的语义,比如作为一个警告图标,这确保了这个图像的含义可以被所有的用户代理传达,包括屏幕阅读器
Pragmatic uses of IMG //img的实际使用
- Use IMG if you intend to have people print your page and you want the image to be included by default. —JayTee
- 使用img:如果你想要。。。
- Use IMG if you rely on browser scaling to render an image in proportion to text size.
- 使用img:如果你依赖浏览器缩放去成比例的渲染一个图片到文本的大小
- Use IMG for multiple overlay images in IE6.
- 使用img:在IE6使用多重覆盖图片
Use IMG with a z-index in order to stretch a background image to fill its entire window.
Note, this is no longer true with CSS3 background-size; see #6 below.- 看第六条
- Using img instead of background-image can dramatically improve performance of animations over a background.
- 使用img代替background-image可以显著的提升背景动画的性能
When to use CSS background-image //何时使用CSS background-image
- Use CSS background images if the image is not part of the content. —sanchothefat
- 使用CSS背景图:如果图片不是内容的一部分
- Use CSS background images when doing image-replacement of text eg. paragraphs/headers. —sanchothefat
- 使用CSS背景图:当做文本的图片替换,例如段落、头部(可能是指图片作为标题头吧)
- Use background-image if you intend to have people print your page and you do not want the image to be included by default. —JayTee
- 使用背景图:如果你想要有人打印你的页面并且不想该图片被包含进去
- Use background-image if you need to improve download times, as with CSS sprites.
- 使用背景图:如果你需要改善下载时间,作为CSS精灵
- Use background-image if you need for only a portion of the image to be visible, as with CSS sprites.
- 使用背景图:如果你只需要图片一部分课件,作为CSS精灵
- Use background-image with background-size:cover in order to stretch a background image to fill its entire window.
- 使用背景图:通过background-size:cover以便伸展一个背景图片去填充满它的整个窗口
先抛开实际操作中的问题,准则其实很简单,如果一张图片是网页内容的一部分,就该用 img ,否则就建议用 CSS 背景图。但问题的核心在于「Logo 是否属于网页内容的一部分」。从语义正确性角度个人倾向于用 img。——顾轶灵
还有一些说法是【A标签+CSS定义背景图】对搜索引擎好,并且看了好多网站也是这么写的(知乎的logo用的就是这种方式,这种方式比IMG好就在于是个很好的锚文本链接,而且A标签也可以添加title属性,而IMG没有锚文本,只有title属性和alt文本。目前来说,搜索引擎对文本信息的识别要比alt中的文字友好的多)
最后说一个知乎前端网红【一丝】建议的方法:同时写背景图片和 img 标签,兼顾SEO 的同时在高对比度模式下也可以正常显示图片。使用 img 还有一个好处是,用户可以很方便的右键保存 Logo 或者复制 Logo 图片的链接,Demo。
1 | <h1 class="logo"> |
1 | .logo a { |
.alt-logo 的作用是当图片加载失败的时候可以显示一个替代文本,如果只用兼容 IE8 以上,可以用 ::after 伪元素代替。
图片加载失败时的展现(Chrome):
好吧,我觉得最后这种方法是照顾的比较全面的,不过貌似复制图片和图片链接的需求很小,所以我觉得一般A标签+CSS定义背景图就够了。