[html] CSS background image alt attribute

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.

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

This question is related to html css

The answer is


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

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

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.

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.

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.


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 function for example:

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.

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)?


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

<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:

/* ==========================================================================
   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%;
}

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

and has examples here 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:

<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 */
}

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.


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 sprites can 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.

The answer is that they don't use alt text at all, but instead use the title attribute on the containing div.

HTML

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

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

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:

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.

You can achieve this by putting the alt tag in the div were your image will appear.

Example:

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

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

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.

I agree with him.


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

<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.


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

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

HTML

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