在CSS中定义<img>的src属性

Mas*_*ues 100 css attributes image

我需要在CSS中定义一个<img>的src属性.有没有办法指定这个属性?

小智 167

就像img标签是一个内容元素一样

img {
    content:url(http://example.com/image.png);
}
Run Code Online (Sandbox Code Playgroud)

  • 这怎么不是被接受的答案?今天我认为这已在浏览器中广泛实现 (3认同)
  • 目前,数据URI仅在Chrome中可用。`content:url(“ data:image / svg + xml,%3csvg xmlns ='http://www.w3.org/2000/svg'width ='181'.....` (2认同)

Ali*_*der 73

#divID {
    background-image: url("http://imageurlhere.com");
    background-repeat: no-repeat;
    width: auto; /*or your image's width*/
    height: auto; /*or your image's height*/
    margin: 0;
    padding: 0;
}
Run Code Online (Sandbox Code Playgroud)

  • @zipcodeman:太糟糕了.`background-image:`方法有一些限制.就像,你无法控制图像的尺寸.当然,您可以使图像空间更大,而不是实际图像. (2认同)
  • @GregoryLewis我认为这更好:http://stackoverflow.com/questions/2182716/how-can-we-specify-src-attribute-of-img-tag-in-css (2认同)
  • @zipcodeman-您可以通过以下方式更改图像的大小:使用`background-size:cover`,然后更改高度和宽度。 (2认同)
  • 今天,2017 年,`background-image` 不是解决方案。制作这个,我有 2 张图片 (2认同)

cle*_*tus 47

不,没有.您可以指定背景图像,但这不是一回事.

  • 确实.`<img>`表示内容图像.如果图像不是内容,则它不应该是`<img>`元素.如果它是内容,那么它应该是.如果内容在多个页面上重复(例如作为菜单的一部分),那么它的HTML也应该是(例如使用模板系统),就像任何其他重复内容一样. (4认同)

Dar*_*rov 11

CSS不用于定义DOM元素属性的值,javascript更适合这个.


RoT*_*oRa 8

不.您可以获得的最接近的是设置背景图像:

<div id="myimage"></div>

#myimage {
  width: 20px;
  height: 20px;
  background: white url(myimage.gif) no-repeat;
}
Run Code Online (Sandbox Code Playgroud)


Eri*_*ric 5

在尝试了这些解决方案后,我仍然不满意,但是在本文中找到了解决方案,并且该解决方案可以在Chrome,Firefox,Opera,Safari,IE8 +中运行

#divId {

  display: block;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  background: url(http://notrealdomain2.com/newbanner.png) no-repeat;
  width: 180px; /* Width of new image */
  height: 236px; /* Height of new image */
  padding-left: 180px; /* Equal to width of new image */

}
Run Code Online (Sandbox Code Playgroud)