I have an image element, to which I've added a different background image using CSS.
img { background-image: url('http://i.stack.imgur.com/5eiS4.png') !important; }
<img src="http://i.stack.imgur.com/smHPA.png" />
I want to show the CSS-specified background image (the Stack Exchange logo) in the image element, instead of the image specified by the src
attribute (the Stack Overflow logo).
Is this possible? I have a situation where I can't alter the HTML or use JavaScript, and am looking for alternatives.
I found a solution that works in all major browsers (tested in IE8+) trying with brute force.
img { background-image: url('http://i.stack.imgur.com/5eiS4.png') !important; position: relative; overflow: hidden; width: 32px; height: 36px; padding: 32px 36px 0 0; box-sizing: border-box; }
<img src="http://i.stack.imgur.com/smHPA.png"/>
It has some tricks. You have to give actual width and height of the image as width and height. Then set the padding left and top to that width and height respectively. I don't know if overflow is relevant but just added it. Box-sizing must be border-box.
Edit: Solution is more minimal. One of padding-left
or padding-top
is enough and there is no need for overflow:hidden
. Fiddle with it.
The object-position
CSS property, which is supported by both Chrome and Firefox, provides a fairly direct solution to this problem. This property is used to offset the rendering position of the native image within its element. The specification helpfully notes that...
Areas of the box not covered by the replaced element will show the element’s background.
...so as long as we provide an offset which ensures the native image will be entirely out-of-bounds, the background will be visible instead. For example:
img { object-position: -99999px 99999px; background-image: url('http://i.stack.imgur.com/5eiS4.png'); }
<img src="http://i.stack.imgur.com/smHPA.png" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With