Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide the src image in an <img> element, but show its background image

Tags:

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.

like image 623
lrtad Avatar asked Aug 28 '13 07:08

lrtad


2 Answers

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.

like image 85
Gokhan Kurt Avatar answered Sep 29 '22 17:09

Gokhan Kurt


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" />
like image 22
Jeremy Avatar answered Sep 29 '22 17:09

Jeremy