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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2676436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 21:55:49  来源:igfitidea点击:

Define an <img>'s src attribute in CSS

cssattributesimage

提问by Massimo Ugues

I need to define an <img>'s src attribute in CSS. Is there a way to specify this attribute?

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

采纳答案by Ali Demirci

#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;
}

回答by Marinos

just this as img tag is a content element

只是这个因为 img 标签是一个内容元素

img {
    content:url(http://example.com/image.png);
}

回答by cletus

No there isn't. You can specify a background image but that's notthe same thing.

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

回答by Darin Dimitrov

CSS is not used to define values to DOM element attributes, javascript would be more suitable for this.

CSS 不用于定义 DOM 元素属性的值,javascript 更适合于此。

回答by RoToRa

No. The closest you can get is setting a background image:

不。最接近的是设置背景图像:

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

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

回答by Eric

After trying these solutions I still wasn't satisfied but I found a solution in this articleand it works in Chrome, Firefox, Opera, Safari, IE8+

在尝试了这些解决方案后,我仍然不满意,但我在本文中找到了一个解决方案,它适用于 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 */

}

回答by Frank

They are right. IMG is a content element and CSS is about design. But, how about when you use some content elements or properties for design purposes? I have IMG across my web pages that must change if i change the style (the CSS).

他们是对的。IMG 是一个内容元素,而 CSS 是关于设计的。但是,当您出于设计目的使用某些内容元素或属性时呢?我的网页上有 IMG,如果我更改样式(CSS),这些 IMG 必须更改。

Well this is a solution for defining IMG presentation (no really the image) in CSS style.
1: create a 1x1 transparent gif or png.
2: Assign propery "src" of IMG to that image.
3: Define final presentation with "background-image" in the CSS style.

嗯,这是在 CSS 样式中定义 IMG 演示文稿(实际上不是图像)的解决方案。
1:创建一个 1x1 透明的 gif 或 png。
2:将 IMG 的属性“src”分配给该图像。
3:在CSS样式中使用“background-image”定义最终演示。

It works like a charm :)

它就像一个魅力:)