Can I replace an image tag’s image with CSS?

2019-09-19 23:30发布

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

i thought something like that: moving the actual image with padding/text-intend etc. out of view and after that setting the background-image of the img-tag, so it looks like an other image.

Js is not an option, because it's about templating an existing page.

4条回答
霸刀☆藐视天下
2楼-- · 2019-09-19 23:42

you could hide the image itself:

img#someid { display: none; }

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

查看更多
Viruses.
3楼-- · 2019-09-19 23:44

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) 0 0 no-repeat; }
img:hover { background: url(sprite.jpg) -50px 0 no-repeat; }
查看更多
The star\"
4楼-- · 2019-09-19 23:44

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.

查看更多
唯我独甜
5楼-- · 2019-09-19 23:52

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.

查看更多
登录 后发表回答