Html CSS 背景图片 alt 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4216035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 05:20:01  来源:igfitidea点击:

CSS background image alt attribute

htmlcss

提问by Sixfoot Studio

This is one I have not had to tackle before. I need to use alt tags on all images in a site including those used by CSS background-image attribute.

这是我以前不必解决的问题。我需要在站点中的所有图像上使用 alt 标签,包括 CSS background-image 属性使用的那些。

There is no CSS property like this as far as I know, so what is the best way to do this please?

据我所知,没有这样的 CSS 属性,那么最好的方法是什么?

回答by Randy Greencorn

Background images sure can present data! In fact, this is often recommended where presenting visual icons is more compact and user-friendly than an equivalent list of text blurbs. Any use of image spritescan benefit from this approach.

背景图片肯定可以呈现数据!事实上,在呈现视觉图标比等效的文本简介列表更紧凑和用户友好的情况下,通常建议这样做。任何图像精灵的使用都可以从这种方法中受益。

It is quite common for hotel listings icons to display amenities. Imagine a page which listed 50 hotel and each hotel had 10 amenities. A CSS Sprite would be perfect for this sort of thing -- better user experience because it's faster. But how do you implement ALT tags for these images? Example site.

酒店列表图标显示便利设施是很常见的。想象一个页面列出了 50 家酒店,每家酒店有 10 种便利设施。CSS Sprite 非常适合这类事情——更好的用户体验,因为它更快。但是如何为这些图像实现 ALT 标签呢?示例站点

The answer is that they don't use alttext at all, but instead use the titleattribute on the containing div.

答案是它们根本不使用alt文本,而是使用title包含 div 上的属性。

HTML

HTML

<div class="hotwire-fitness" title="Fitness Centre"></div>

CSS

CSS

.hotwire-fitness {
    float: left;
    margin-right: 5px;
    background: url(/prostyle/images/new_amenities.png) -71px 0;
    width: 21px;
    height: 21px;
}

According to the W3C (see links above), the title attribute serves much of the same purpose as the alt attribute

根据 W3C(请参阅上面的链接),title 属性与 alt 属性的用途大致相同

Title

标题

Values of the title attribute may be rendered by user agents in a variety of ways. For instance, visual browsers frequently display the title as a "tool tip" (a short message that appears when the pointing device pauses over an object). Audio user agents may speak the title information in a similar context. For example, setting the attribute on a link allows user agents (visual and non-visual) to tell users about the nature of the linked resource:

title 属性的值可以由用户代理以多种方式呈现。例如,可视化浏览器经常将标题显示为“工具提示”(当指针设备停在对象上时出现的一条短消息)。音频用户代理可以在类似的上下文中说出标题信息。例如,在链接上设置属性允许用户代理(视觉和非视觉)告诉用户链接资源的性质:

alt

alt

The alt attribute is defined in a set of tags (namely, img, area and optionally for input and applet) to allow you to provide a text equivalent for the object.

A text equivalent brings the following benefits to your website and its visitors in the following common situations:

  • nowadays, Web browsers are available in a very wide variety of platforms with very different capacities; some cannot display images at all or only a restricted set of type of images; some can be configured to not load images. If your code has the alt attribute set in its images, most of these browsers will display the description you gave instead of the images
  • some of your visitors cannot see images, be they blind, color-blind, low-sighted; the alt attribute is of great help for those people that can rely on it to have a good idea of what's on your page
  • search engine bots belong to the two above categories: if you want your website to be indexed as well as it deserves, use the alt attribute to make sure that they won't miss important sections of your pages.

alt 属性在一组标签(即 img、area 以及可选的 input 和 applet)中定义,以允许您为对象提供等效的文本。

在以下常见情况下,等效文本可为您的网站及其访问者带来以下好处:

  • 如今,Web 浏览器可用于各种不同容量的平台;有些根本无法显示图像,或者只能显示一组受限制的图像类型;有些可以配置为不加载图像。如果您的代码在其图像中设置了 alt 属性,大多数浏览器将显示您提供的描述而不是图像
  • 您的一些访问者无法看到图像,无论他们是盲人、色盲还是弱视;alt 属性对于那些可以依靠它来很好地了解您页面上的内容的人有很大帮助
  • 搜索引擎机器人属于上述两个类别:如果您希望您的网站得到应有的索引,请使用 alt 属性以确保它们不会错过您页面的重要部分。

回答by Ian Lunn

In this Yahoo Developer Network(archived link) article it is suggested that if you absolutely mustuse a background-image instead of img element and alt attribute, use ARIA attributes as follows:

在这篇雅虎开发者网络存档链接)文章中,建议如果您绝对必须使用 background-image 而不是 img 元素和 alt 属性,请使用 ARIA 属性,如下所示:

<div role="img" aria-label="adorable puppy playing on the grass">
  ...
</div>

The use case in the article describes how Flickr chose to use background images because performance was greatly improved on mobile devices.

文章中的用例描述了 Flickr 如何选择使用背景图像,因为性能在移动设备上得到了极大的提升。

回答by C???

I think you should read this postby Christian Heilmann. He explains that background images are ONLYfor aesthetics and should not be used to present data, and are therefore exempt from the rule that every image should have alternate-text.

我认为您应该阅读Christian Heilmann 的这篇文章。他解释说,背景图像用于美观,不应用于呈现数据,因此不受每个图像都应具有替代文本的规则的约束。

Excerpt (emphasis mine):

摘录(强调我的):

CSS background images which are by definition only of aesthetic value – not visual content of the document itself. If you need to put an image in the page that has meaning then use an IMG element and give it an alternative text in the alt attribute.

CSS 背景图像根据定义仅具有审美价值 - 而不是文档本身的视觉内容。如果您需要在页面中放置有意义的图像,请使用 IMG 元素并在 alt 属性中为其提供替代文本。

I agree with him.

我同意他的看法。

回答by javaBean007

As mentioned in other answers, there is no (supported) alt attribute for a div tag only for the img tag.

如其他答案中所述,仅 img 标签的 div 标签没有(支持的)alt 属性。

The real question is why you need to add the alt attribute to all background imagesfor the site? Based on this answer, it will help you determine which route to take in your approach.

真正的问题是为什么您需要为网站的所有背景图片添加 alt 属性?基于此答案,它将帮助您确定在您的方法中采用哪条路线。

Visual/Textual:If you are simply attempting to add a textual fall back for the user if the image fails to load, simply use the title attribute. Most browsers will provide a visual tool tip(message box) when a user hovers over the image, and if the image is not loaded for whatever reason, it behaves the same as an alt attribute presenting text when image fails. This technique still allows for the site to speed up load times by keeping images set to backgrounds.

视觉/文本:如果您只是尝试在图像加载失败时为用户添加文本回退,只需使用标题属性。当用户将鼠标悬停在图像上时,大多数浏览器会提供一个可视化工具提示(消息框),如果由于某种原因没有加载图像,它的行为与图像失败时呈现文本的 alt 属性相同。这种技术仍然允许网站通过将图像设置为背景来加快加载时间。

Screen Readers:The middle of the road option, this varies because technically keeping your images as backgrounds and using the title attribute approach should work as hinted above, "Audio user agents may speak the title information in a similar context."However this is not guaranteed to work in all cases, including some readers may ignore it all together. If you end up opting for this approach, you can also try adding in aria-labels to help ensure screen readers pick these up.

屏幕阅读器:中间选项,这会有所不同,因为从技术上讲,将您的图像作为背景并使用标题属性方法应该如上面所暗示的那样工作,“音频用户代理可能会在类似的上下文中说出标题信息。” 然而,这并不能保证在所有情况下都有效,包括一些读者可能会一起忽略它。如果您最终选择了这种方法,您还可以尝试添加 aria-labels 以帮助确保屏幕阅读器选择这些。

SEO/Search Engines:Here is the big one, if you were like me, you added your background images, all was good. Then months later the customer(or maybe yourself) realized that you are missing out on some prime SEO gold by not having alt's for your images. Keep in mind, the title attribute does not have any weight on search engines, from my research and as mentioned in an article here: https://www.searchenginejournal.com/how-to-use-link-title-attribute-correctly/. So if you are aiming for SEO, then you will need to have an img tag with the alt attribute. One possible approach is to just load very small actual images on the site with alt attributes, this way you get all the SEO and don't have to readjust the existing CSS in place. However this may lead to additional load time depending on the size and google does indeed look at the images path when indexing. In short if you are going this route, just accept what has to be done and include the actual images instead of using backgrounds.

SEO/搜索引擎:这是最重要的,如果你像我一样,你添加了你的背景图片,一切都很好。然后几个月后,客户(或者您自己)意识到,由于您的图片没有替代品,您错过了一些主要的 SEO 黄金。请记住,标题属性对搜索引擎没有任何权重,根据我的研究以及此处的文章中所述:https: //www.searchenginejournal.com/how-to-use-link-title-attribute-correctly /. 因此,如果您的目标是 SEO,那么您将需要一个带有 alt 属性的 img 标签。一种可能的方法是只在站点上加载带有 alt 属性的非常小的实际图像,这样您就可以获得所有 SEO,而不必重新调整现有的 CSS。然而,这可能会导致额外的加载时间,具体取决于大小,谷歌在索引时确实会查看图像路径。简而言之,如果您要走这条路,只需接受必须完成的工作并包含实际图像而不是使用背景。

回答by commonpike

This article from W3C tells you what they think you should do https://www.w3.org/WAI/GL/wiki/ARIATechnique_usingImgRole_with_aria-label_forCSS-backgroundImage

W3C 的这篇文章告诉你他们认为你应该做什么 https://www.w3.org/WAI/GL/wiki/ARIATechnique_usingImgRole_with_aria-label_forCSS-backgroundImage

and has examples here http://mars.dequecloud.com/demo/ImgRole.htm

并在此处提供示例 http://mars.dequecloud.com/demo/ImgRole.htm

among which

在这之中

<a href="http://www.facebook.com">
 <span class="fb_logo" role="img" aria-label="Connect via Facebook">
 </span>
</a>

Still, if, like in the above example, the element containing the background image is just an empty container, I personally prefer to put the text in there and hide it using CSS; right where you show the image instead:

尽管如此,如果像上面的例子一样,包含背景图像的元素只是一个空容器,我个人更喜欢将文本放在那里并使用 CSS 隐藏它;就在你显示图像的地方:

<a href="http://www.facebook.com"><span class="fb_logo">
  Connect via Facebook
</span></a>

.fb_logo {
  height: 37px; width: 37px;
  background-image: url('../gfx/logo-facebook.svg');
  color:transparent; overflow:hidden; /* hide the text */
}

回答by emik

The classical way to achieve this is to put the text into the div and use an image replacement technique.

实现这一点的经典方法是将文本放入 div 并使用图像替换技术。

<div class"ir background-image">Your alt text</div>

with background-image beeing the class where you assign the background image and ir could be HTML5boilerplates image replacement class, below:

使用 background-image beeing 分配背景图像的类,ir 可以是 HTML5boilerplates 图像替换类,如下所示:

/* ==========================================================================
   Helper classes
   ========================================================================== */

/*
 * Image replacement
 */

.ir {
    background-color: transparent;
    border: 0;
    overflow: hidden;
    /* IE 6/7 fallback */
    *text-indent: -9999px;
}

.ir:before {
    content: "";
    display: block;
    width: 0;
    height: 150%;
}

回答by ameer

The general belief is that you shouldn't be using background images for things with meaningful semantic value so there isn't really a proper way to store alt data with those images. The important question is what are you going to be doing with that alt data? Do you want it to display if the images don't load? Do you need it for some programmatic function on the page? You could store the data arbitrarily using made up css properties that have no meaning (might cause errors?) OR by adding in hidden images that have the image and the alt tag, and then when you need a background images alt you can compare the image paths and then handle the data however you want using some custom script to simulate what you need.There's no way I know of to make the browser automatically handle some sort of alt attribute for background images though.

一般的看法是,您不应该将背景图像用于具有有意义的语义值的事物,因此没有真正正确的方法将替代数据与这些图像一起存储。重要的问题是你打算用这些替代数据做什么?如果图像未加载,您是否希望它显示?页面上的某些编程功能需要它吗?您可以使用没有意义的组成 css 属性(可能会导致错误?)或通过添加具有图像和 alt 标签的隐藏图像来任意存储数据,然后当您需要背景图像 alt 时,您可以比较图像路径,然后处理数据,但是您想要使用一些自定义脚本来模拟您需要的内容。我不知道让浏览器自动处理背景图像的某种 alt 属性。

回答by sloga

Here's my solution to this type of problem:

这是我对此类问题的解决方案:

Create a new class in CSS and position off screen. Then put your alt text in HTML right before the property that calls your background image. Can be any tag, H1, H2, p, etc.

在 CSS 中创建一个新类并在屏幕外定位。然后将您的替代文本放在 HTML 中调用背景图像的属性之前。可以是任何标签H1H2p、 等。

CSS

CSS

<style type="text/css">
  .offleft {
    margin-left: -9000px;
    position: absolute;
  }
</style>

HTML

HTML

<h1 class="offleft">put your alt text here</h1>
<div class or id that calls your bg image>  </div>

回答by ChrisW

It''s not clear to me what you want.

我不清楚你想要什么。

If you want a CSS property to render the alt attribute value, then perhaps you're looking for the CSS attribute functionfor example:

如果您想要一个 CSS 属性来呈现 alt 属性值,那么您可能正在寻找CSS 属性函数,例如:

IMG:before { content: attr(alt) }

If you want to put the alt attribute on a background image, then ... that's odd because the alt attribute is an HTML attribute whereas the background image is a CSS property. If you want to use the HTML alt attribute then I think you'd need a corresponding HTML element to put it in.

如果您想将 alt 属性放在背景图像上,那么……这很奇怪,因为 alt 属性是一个 HTML 属性,而背景图像是一个 CSS 属性。如果您想使用 HTML alt 属性,那么我认为您需要一个相应的 HTML 元素来放入它。

Why do you "need to use alt tags on background images": is this for a semantic reason or for some visual-effect reason (and if so, then what effect or what reason)?

为什么“需要在背景图像上使用 alt 标签”:这是出于语义原因还是出于某种视觉效果原因(如果是,那么是什么效果或什么原因)?

回答by Alverto

You can achieve this by putting the alttag in the divwere your image will appear.

您可以通过将alt标签放在div您的图像将出现的位置来实现此目的。

Example:

例子:

<div id="yourImage" alt="nameOfImage"></div>