1

I have write <img> tag like this :

<img id="image1" alt="image1" />

And css code is :

#image1 {
    background-image: url("../images/home-page/image1.jpg");
    background-size: 100% 100%;
    position: absolute;
}

On my web page image and alt attribute's text both gets displayed. If image is present then I don't want to display alt text. Don't know what is the problem. Can anyone knows How to solve it? And what is the problem?

Tejashri Bedarkar
  • 139
  • 1
  • 1
  • 9
  • 1
    Better explanation here - http://stackoverflow.com/questions/492809/when-to-use-img-vs-css-background-image and another here http://stackoverflow.com/questions/17288500/img-vs-background-image-css-in-performance – Pugazh Jul 05 '16 at 07:11
  • 4
    Give the image a `src` attribute, and remove the background image …? – CBroe Jul 05 '16 at 07:11
  • I used different sizes of images for different resolution. If I used `src` then how can i change that image? It always use image given in `src` attribute. – Tejashri Bedarkar Jul 05 '16 at 07:19

3 Answers3

6

It displays the alt text because the image failed to load. The image failed to load because it doesn't have a src attribute.

  • If you want a content image, then use a src attribute.
  • If you want a background image, then don't use an <img> element.

I used different sizes of images for different resolution.

Then you want the <picture> element:

<picture>
  <source 
    media="(min-width: 650px)"
    srcset="images/kitten-stretching.png">
  <source 
    media="(min-width: 465px)"
    srcset="images/kitten-sitting.png">
  <img 
    src="images/kitten-curled.png" 
    alt="a cute kitten">
</picture>

Example via HTML5 Rocks

Quentin
  • 857,932
  • 118
  • 1,152
  • 1,264
1

alt attribute specifies an alternate text for an image, if the image cannot be displayed.

Here in this scenario alt is displayed as src is mising.

I could think of 2 solutions.

  1. Keep alt text blank if you don't wish to see any text.

  2. Use a div and specify the background-image.

Pugazh
  • 9,257
  • 5
  • 30
  • 51
0

As far as I know, youn can use the alt attribute only with a src attribute. Excluding the src will always lead the alt to get displayed (as it's happening in your example). So in your case, you would do something like that:

<img id="image1" alt="image1" src="../images/home-page/image1.jpg" />

#image1 {
/* This is obsolete, as @Pugazh already mentioned (you better use fix values) */
    background-size: 100% 100%;
    position: absolute;
}

You can also see this fiddle.

Aer0
  • 3,559
  • 16
  • 31
  • While adding `src` to the image, `background-size: 100% 100%;` doesn't mean anything. You should specify `width` and `height` to control the image size – Pugazh Jul 05 '16 at 07:20
  • 1
    You're pretty much right. In this case that's kinda obsolete, yet I only used his shared snippet for demonstrational purpose. – Aer0 Jul 05 '16 at 07:22