如何把图像与CSS的div?

我想我所有的图像在CSS(我知道如何把他们作为背景图像的唯一方法)。

但是这个解决scheme的问题是你永远不能让div取得图像的大小。

所以我的问题是:在CSS中具有相当于<div><img src="..." /></div>的最佳方式是什么?

Jaap回答:

 <div class="image"></div>​ 

在CSS中:

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

你可以试试这个链接: http : //jsfiddle.net/XAh2d/

这是一个关于CSS内容的链接http://css-tricks.com/css-content/

这已经过Chrome,Firefox和Safari的testing。 (我在Mac上,所以如果有人在IE浏览器上的结果,告诉我添加它)

你可以这样做:

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

并把它放到你的css文件中:

 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 */ } 

否则,只要使用它们就可以

用Javascript / jquery:

  • 加载图像与隐藏的img
  • 当图像已经加载,获得宽度和高度
  • dynamic创build一个div并设置宽度,高度和背景
  • 删除原来的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"); }); 

以此作为示例代码。 将imageheight和图像宽度replace为图像尺寸。

 <div style="background:yourimage.jpg no-repeat;height:imageheight px;width:imagewidth px"> </div>