How to put image in div using CSS?

I would like to have all my images in CSS (the only way I know how to place them as background images).

But the problem with this solution is that you cannot let the div take the size of the image.

So my question is: what is the best way to get the <div><img src="..." /></div> equivalent in CSS?

+70
css image
May 31 '12 at 8:07
source share
4 answers

This Jaap answer:

 <div class="image"></div>โ€‹ 

and in CSS:

 div.image { content:url(http://placehold.it/350x150); }โ€‹ 

you can try it at this link: http://jsfiddle.net/XAh2d/

this is a link about css content http://css-tricks.com/css-content/

This has been tested in Chrome, firefox and Safari. (I'm on mac, so if anyone has a result in IE, tell me add it)

+95
May 31 '12 at 12:32
source share

You can do it:

 <div class="picture1">&nbsp;</div> 

and put this in your css file:

 div.picture1 { width:100px; /*width of your image*/ height:100px; /*height of your image*/ background-image:url('yourimage.file'); margin:0; /* If you want no margin */ padding:0; /*if your want to padding */ } 

otherwise, just use them as normal

+11
May 31 '12 at 8:14
source share

With Javascript / JQuery:

  • upload image with hidden img
  • When the image is loaded, get the width and height
  • dynamically create div and set width, height and background
  • remove the original img

      $(document).ready(function() { var image = $("<img>"); var div = $("<div>") image.load(function() { div.css({ "width": this.width, "height": this.height, "background-image": "url(" + this.src + ")" }); $("#container").append(div); }); image.attr("src", "test0.png"); }); 
+4
May 31 '12 at 8:24 a.m.
source share

Take this as an example of code. Replace imageheight and image width with your image size.

 <div style="background:yourimage.jpg no-repeat;height:imageheight px;width:imagewidth px"> </div> 
+3
May 31 '12 at 8:16
source share



All Articles