Skip to content Skip to sidebar Skip to footer

Can I Replace An Image Tag’s Image With Css?

I know I can't change the src attribute of an tag with CSS. But is there a possiblity to hide the image from the src attribute, and set a background image on the

Solution 1:

you could hide the image itself:

img#someid { display: none; }

and then (or before that if you wish) set background on the parent element.

Solution 2:

You can do that by pointing the img src to a 1x1 blank gif image.

This is necessary if you don't want to add another div since all browsers handle missing images and empty src attributes differently. (chrome will add a border around the image if the image is missing for instance.)

Then you can change the images just by changing the background-image property.

UPDATE

You can also create image sprites for that and animate them by altering the background-position property. For instance:

Lets say that you have two 50px wide images and you want the second one to show when that element is hovered. Just merge them together in one image, and the css above would do the trick.

img { background: url(sprite.jpg) 00 no-repeat; }
img:hover { background: url(sprite.jpg) -50px0 no-repeat; }

Solution 3:

I'm not quite sure what you mean with 'hide the image of the src attribute' but if you mean hide the link/path of the image you are displaying, using CSS (even as a background image) then the answer is no, not that I'm aware of. People can easily view your CSS file. The only real way to hide it is with JS, but even with that you can disable the JS from the client and still view it. You could put it in a DB like MySQL and display it using PHP but even at that, the image path would still be shown.

Solution 4:

Would you be able to wrap the img in a div with no padding/margin, and make the img's display attribute to hidden (via js) so the div's background would be shown.

But honestly, if you take the trouble to do this, you should just swap the src of the image via js.

Post a Comment for "Can I Replace An Image Tag’s Image With Css?"