skip to Main Content

I have a site with an image at the top of the page. The site is fully responsive.

For the desktop view, I have a specific image I load for the header on the site. For the mobile view, I have a different image.

In the CSS, I use something like:

 .headerimage { background:url(/images/header-desktop.png) no-repeat top left; }

 @media only screen and (max-width: 480px) {
    .headerimage { background:url(/images/header-mobile.png) no-repeat top left; }
 }

And in the HTML it’s just <div class='headerimage'></div>

My question is: how can I add ALT text (like I would to an IMG) tag so my site is fully accessible for screen readers, I get the SEO benefits of alt text, etc.? Obviously I can switch to using an IMG tag but that would require some serious hacks to keep it responsive once I have two IMG tags to deal with.

3

Answers


  1. You can’t without resorting to Javascript AFAIK.

    Using only CSS, your best option to have some description of the background image in your code is to use the title attribute in the DIV tag.

    See here :

    CSS background image alt attribute

    CSS or Javascript – display fallback text if background image not loaded

    Login or Signup to reply.
  2. HTML 5 introduces the picture element which allows you to specify a series of images with media queries.

    <picture>
     <source srcset="/images/header-mobile.png" media="only screen and (max-width: 480px)">
     <img src="/images/header-desktop.png" alt="Foo">
    </picture>
    
    Login or Signup to reply.
  3. Add a broken image, a hack.

    Pseudo elements work for broken images. Read here

    Use the pseudo elements to show other images on breakpoints.

    img::before {
      content: "";
      background-image: url('http://lorempizza.com/200/200');
      width: 200px;
      height: 200px;
      display: block;
      position: absolute;
    }
    
    @media (max-width: 400px) {
      img::before {
        background-image: url('http://placehold.it/200X200')
      }
    }
    

    Fiddle

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search