Latest: Genstatic, my first sip of coffee

Content with Style

Web Technique

CSS Background image on html image element?

by Pascal Opitz on September 15 2008, 07:01

My co-worker Paul showed how helpful it is to question the obvious: Can you apply a background image to an image?

And, as he found out, the answer is: Yes!

Switch the image to display: block, apply a padding, and there you go, you can set up backgrounds for images …

See the little demo I’ve built to achieve a paralax like scrolling with just a div and an img.

Comments

  • yes, I’ve made some things like this when I needed double border on images.

    img{
    display:block;
    padding:1px;
    background:red;
    border:1px solid black;
    }

    by icaaq on September 12 2008, 05:35 - #

  • I do this when I want to overlay something on another image. For example, if I want a product to have an “on sale” overlay, and don’t want to edit the actual product shot, I’ll set the image to the “on sale” graphic with a transparent background and use the product shot as the background.

    by Dave Child on September 12 2008, 06:00 - #

  • @dave child: not very semantic to use the actual product shot as a background-image. I don’t have any easy “this-is-how-i-should-have-done” thing, but that doesn’t seems quite right..

    by icaaq on September 12 2008, 09:05 - #

  • The technique you have described rocks, however, there is a little caveat that should be considered upon using it – Internet Explorer cannot render background images of image tags in quirks mode.

    by Martin Ivanov on September 15 2008, 06:31 - #

  • Martin: Thanks for pointing this out. I guess this is another good reason for everyone to decide which Doctype you’re choosing before you start coding the site templates.

    by Pascal Opitz on September 15 2008, 07:13 - #

  • Awesome.

    by Nisheeth on December 3 2008, 10:34 - #

  • if product's image is placed as a background image one have to remember that it would not be indexed by search-engines. so you can use this technique only if you don't need seo for this particular image if you still need seo, ... it is better to use z-indexed “on sale” overlay i assume.

    by kattykatty on December 20 2008, 16:13 - #

  • i noticed your parallax demo using the image background tag is 404 - any chance you still have it around someplace or can explain what you did? i'm curious to see what you achieved. i discovered this little wonder of css a few weeks ago and have been trying to figure out what cool things i can do with it ever since ;)

    by jamie on August 11 2010, 12:51 - #

  • Sorry about this, it's been relocated here.

    by Pascal Opitz on August 11 2010, 17:58 - #


Comments for this article are closed.