675

Is it possible to set the src attribute value in CSS?
In most cases, we use it like this:

<img src="pathTo/myImage.jpg" />

and I want it to be something like this

<img class="myClass" />
.myClass {
    some-src-property: url("pathTo/myImage.jpg");
}

I want to know if there is a way doing it without using the background or background-image properties in CSS.

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
Rakesh Juyal
  • 35,919
  • 68
  • 173
  • 214

24 Answers24

1111

Use content:url("image.jpg").

Full working solution (Live Demo):

<!doctype html>

<style>
.MyClass123{
    content:url("http://imgur.com/SZ8Cm.jpg");
}
</style>

<img class="MyClass123"/>

Tested and working:

  • Chrome 14.0.835.163
  • Safari 4.0.5
  • Opera 10.6
  • Firefox 100 & newer

Tested and Not working:

  • FireFox 40.0.2 (observing Developer Network Tools, you can see that the URL loads, but the image is not displayed)
  • Internet Explorer 11.0.9600.17905 (URL never loads)
Alan H.
  • 16,219
  • 17
  • 80
  • 113
Pacerier
  • 86,231
  • 106
  • 366
  • 634
  • 2
    The content property should be used with a pseudo tag, see http://www.w3schools.com/cssref/pr_gen_content.asp – Rob Audenaerde Dec 18 '12 at 07:57
  • 7
    @gotqn, only Chrome Safari Opera so far. – Pacerier Jan 10 '13 at 13:39
  • 40
    @EricG, different applications have different requirements. If it doesn't suit your requirements, don't use it. If it does, use it. – Pacerier Feb 22 '13 at 12:17
  • 1
    I think you can only use it with :after and :before – mlwacosmos Mar 08 '13 at 15:29
  • @RobAu and @mlwacosmos, no. The `content` property applies to all elements. [http://www.w3.org/TR/css3-content/#content](http://www.w3.org/TR/css3-content/#content) – XP1 May 02 '13 at 15:25
  • 1
    @XP1 That depends on the CSS version you use. CSS3 supports content everywhere, whereas CSS2.1 only allows :before and :after. – Rob Audenaerde May 17 '13 at 12:39
  • Unfortunately this method is useless if you are using sprites. The background-image property is still the only all-terrain solution. – GetFree Jun 02 '13 at 13:56
  • 5
    Not working IE10 is a no-go. We ditch IE7 (let's not talk about IE6). IE8 too, if needed. But IE9 - IE10... no. – Rolf Jun 17 '13 at 10:09
  • 1
    Doesn't work properly in every browser. See http://jsfiddle.net/krnlde/2VC4v/ for reference. – kernel Jul 10 '13 at 14:33
  • 18
    Worth to add that even in browsers that support assigning `content` to `img`, it changes its behavior. The image starts to ignore size attributes, and in Chrome/Safari it loses the context menu options like 'Save image'. This is because assigning a `content` effectively converts `img` from _empty replaced_ element to something like ``. – Ilya Streltsyn Jul 14 '13 at 22:55
  • This works for me in android 2.3 WebView and Chrome... of course – Ben Jul 26 '13 at 22:24
  • 3
    without proper browser support I don't see this as a valid answer, sorry. – emachine Aug 30 '13 at 17:37
  • FYI, there is another downside to this if you pre-set the src-attribute of the `` tag with an url (e.g. for seo) and you'd like to overwrite it via css property `content:url(...)` then BOTH images will be loaded which again produces network overhead. – Timo Ernst Dec 12 '13 at 11:49
  • @Timo, which browser actually loads it twice? And assuming that is right, the overhead should be pretty low for properly cached images. – Pacerier Dec 14 '13 at 05:40
  • @Pacerier Missunderstanding. In my note I was talking about 2(!) different images. A low-res one for the src-attribute of the image and a high-res one for retina displays which is set via `content:url(...)`. I tested on Google Chrome and it loaded both images although only 1 would be enough. – Timo Ernst Dec 16 '13 at 14:18
  • 2
    Incredibly, this does work on Android 2.3 but it does not on Firefox 30. – andreszs Jan 19 '15 at 05:33
  • 3
    @XP1: Keep in mind that that particular draft of css3-content is an abandoned draft that was last modified a decade ago at the time you posted your comment - CSS *2* has had more than a few updates since. There is a very good reason Moz/MS have not implemented it - as far as they are concerned, *that module does not exist*, and thus `content` applies *only* to `::before` and `::after`. It is being resurrected here: http://dev.w3.org/csswg/css-content with a big red warning that says "Not Ready For Implementation" - so I wouldn't bank on authors being able to use it cross-browser any time soon. – BoltClock Mar 31 '15 at 01:54
  • I'm surprised no one has linked to http://caniuse.com/#feat=css-gencontent yet. Shows the browsers supported and known issues. – adam0101 Apr 29 '15 at 13:36
  • @adam0101, That page doesn't show the status for `content:url("image.jpg")`. The charts there are showing all green but it still doesn't work for IE and FF. – Pacerier May 24 '15 at 23:32
  • 2
    @EricG - Because browser quirks shouldn't be the developer's problem. If the browser doesn't respond correctly to the code, that's a problem for the people who make that browser to fix. And if a user makes use of a browser before the browser vendor has fixed it, then that's simply user-error. This solution solves the developer's problem. The rest is up to the good people at Mozilla and Microsoft to fix. – aroth Jun 22 '15 at 08:04
  • 1
    @aroth I think I was just frustrated over a (for me) incomplete solution that (perhaps I) was expected to solve, ofcourse it's a good solution if it helps people. – EricG Jun 23 '15 at 10:18
  • I couldn't use the solution since it doesn't support all browsers I need. I worked out another solution that helped me (might not work for all of you, but it should work in all Css3 compatible browsers). and here it is: I took a background-image fallback for images without src: updated fiddle: [link](http://jsfiddle.net/3BRN7/669/) – jBear Graphics Jul 22 '15 at 17:24
  • Thank you, this snippet just helped me save huge amount of $$ :) :) :) – DamianoPantani Aug 15 '16 at 18:57
  • 3
    Still does not work in Firefox 66.0.3, in case anybody was wondering, although you can still see the network request for the image. – Spencer D Apr 29 '19 at 00:56
  • Content property is not good for img tag. Its not valid html. – Billu Apr 30 '19 at 08:07
  • Is there a way to use this in a JSON notation? something like: imageContent['content'] = url("imageurl.jpg") this doesn't seem to work in react. – NoobNewb Jul 18 '19 at 21:28
  • 2
    It may be worth noting that the images loaded via CSS `content:` will have a much lower load priority than those loaded via the `src` tag (assuming the IMG element is immediately visible). This could be useful for having your IMG elements load a lowres placeholder in their src tags, and a highres image in the CSS content. On the flipside, it could cause issues if you're completely depending on CSS `content:` to load in immediately-visible, high-priority images (such as a website logo) with no lowres placeholders. – Leaf Nov 09 '21 at 01:23
  • 2
    I used this method within a media query and it works great. I tested it on chrome, firefox, edge and vivaldi. – José Rasmussen Jan 21 '22 at 15:19
  • 1
    This works hover on `:hover` it causes a flash of no image. – chovy Mar 05 '22 at 23:46
  • Hover-based demo based on your JSFiddle: https://jsfiddle.net/alanhogan/076qzp25/ – Alan H. Jul 14 '22 at 19:15
194

There is a solution that I found out today (works in IE6+, FF, Opera, Chrome):

<img src='willbehidden.png' 
 style="width:0px; height:0px; padding: 8px; background: url(newimage.png);">

How it works:

  • The image is shrunk until no longer visible by the width & height.
  • Then, you need to 'reset' the image size with padding. This one gives a 16x16 image. Of course you can use padding-left / padding-top to make rectangular images.
  • Finally, the new image is put there using background.
  • If the new background image is too large or too small, I recommend using background-size for example: background-size:cover; which fits your image into the allotted space.

It also works for submit-input-images, they stay clickable.

See live demo: http://www.audenaerde.org/csstricks.html#imagereplacecss

Enjoy!

PJ Brunet
  • 3,615
  • 40
  • 37
Rob Audenaerde
  • 19,195
  • 10
  • 76
  • 121
  • 6
    @RobAnu: This works quite well - [jsfiddle](http://jsfiddle.net/TimPietrusky/R7gQn) – TimPietrusky May 29 '12 at 09:26
  • 9
    Got to hand it to you that this is fascinating and clever, but an empty DIV is more straight-forward. – Volomike Jul 10 '12 at 22:46
  • 13
    In this case it is. There are cases however, where you cannot control the HTML and want to manipulate the IMG nonetheless. There this solution will also work – Rob Audenaerde Jul 11 '12 at 09:41
  • 1
    +1 nice suggestion. Check this modified [fiddle](http://jsfiddle.net/R7gQn/4/) of the above comment. – Mr_Green May 29 '13 at 07:47
  • 2
    If the image has a `src` attribute, this is the technique you need. +1 - helped me a lot – James Long Jun 21 '13 at 07:53
  • 3
    Not ranking on this answer, which might be the solution for some applications, but this method has a limitation. You have no control over the dimensions of the rendering of the image file. In normal use, you can control the height-width of an image, if the file is specified in the source. But this is basically no different from a div with a background image, where if your div is bigger than the image, you're out of luck. – TARKUS Nov 25 '13 at 18:28
  • 1
    In case I'm missing something, is there any reason to use this approach in a situation where you control the HTML? Perhaps this answer could be enhanced by mentioning when it makes sense to use this approach and when it makes sense to simply use an empty div. – Mark Amery Dec 02 '13 at 18:28
  • Not really, structure wise it would make sense to use IMG for images. Or if you do not wish to change all your HTML code.. – Rob Audenaerde Dec 02 '13 at 18:33
  • 1
    Wow, sneaky technique, which works nice when the image is hard-coded and you only have access to a css file. To target the image with css: img[src$="image.png"] ($= is ends with http://www.w3schools.com/cssref/css_selectors.asp ) – GDmac Mar 02 '14 at 12:01
  • 1
    this should be the accepted answer, cross browser and very nice trick ! – Ilian Andreev May 17 '14 at 13:07
  • Does not answer the op's requirement (which is the same as mine). "I don't want to use the background or background-image". This answer deserves a markdown for that (as well as the fact that a div can do this much more elegantly) – cmroanirgo Jun 28 '14 at 00:33
  • This was the perfect solution for my needs. I could not easily change the HTML and did not want to make changes to the HTML when the need to replace the image only exists on a handful pages out of thousands that are all using the same html. Great trick! – David Colby Nov 04 '14 at 17:36
  • 2
    Clever, but it should be noted that this solution does not affect the results of a 'Save Image' or 'Copy Image URL' action...in those cases, you will still get the image defined in the `src` attribute. – Shaun Scovil Feb 04 '15 at 17:52
133

A collection of possible methods to set images from CSS


CSS2's :after pseudo-element or the newer syntax ::after from CSS3 along with the content: property:

First W3C Recommendation: Cascading Style Sheets, level 2 CSS2 Specification 12 May 1998
Latest W3C Recommendation: Selectors Level 3 W3C Recommendation 29 September 2011

This method appends content just after an element's document tree content.

Note: some browsers experimentally render the content property directly over some element selectors disregarding even the latest W3C recommendation that defines:

Applies to: :before and :after pseudo-elements

CSS2 syntax (forward-compatible):

.myClass:after {
  content: url("somepicture.jpg");
}

CSS3 Selector:

.myClass::after {
  content: url("somepicture.jpg");
}

Default rendering: Original Size (does not depend on explicit size declaration)

This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML). This will be defined in more detail in a future specification.

but even at the time of this writing, behaviour with a <IMG> tag is still not defined and although it can be used in a hacked and non standards compliant way, usage with <img> is not recommended!

Great candidate method, see conclusions...



**CSS1**'s [`background-image:`](http://www.w3.org/TR/REC-CSS1-961217#background-image) property:

First W3C Recommendation: Cascading Style Sheets, level 1 17 Dec 1996

This property sets the background image of an element. When setting a background image, one should also set a background color that will be used when the image is unavailable. When the image is available, it is overlaid on top of the background color.

This property has been around from the beginning of CSS and nevertheless it deserve a glorious mention.

Default rendering: Original Size (cannot be scaled, only positioned)

However,

CSS3's background-size: property improved on it by allowing multiple scaling options:

Latest W3C Status: Candidate Recommendation CSS Backgrounds and Borders Module Level 3 9 September 2014

[length> | <percentage> | auto ]{1,2} | cover | contain

But even with this property, it depends on container size.

Still a good candidate method, see conclusions...



CSS2's list-style: property along with display: list-item:

First W3C Recommendation: Cascading Style Sheets, level 2 CSS2 Specification 12 May 1998

list-style-image: property sets the image that will be used as the list item marker (bullet)

The list properties describe basic visual formatting of lists: they allow style sheets to specify the marker type (image, glyph, or number)

display: list-item — This value causes an element (e.g., <li> in HTML) to generate a principal block box and a marker box.

.myClass {
    display: list-item;
    list-style-position: inside;
    list-style-image: url("someimage.jpg");
}

Shorthand CSS: (<list-style-type> <list-style-position> <list-style-image>)

.myClass {
    display: list-item;
    list-style: square inside url("someimage.jpg");
}

Default rendering: Original Size (does not depend on explicit size declaration)

Restrictions:

-

Inheritance will transfer the 'list-style' values from OL and UL elements to LI elements. This is the recommended way to specify list style information.

They do not allow authors to specify distinct style (colors, fonts, alignment, etc.) for the list marker or adjust its position

This method is also not suitable for the <img> tag as the conversion cannot be made between element types, and here's the limited, non compliant hack that doesn't work on Chrome.

Good candidate method, see conclusions...



CSS3's border-image: property recommendation:

Latest W3C Status: Candidate Recommendation CSS Backgrounds and Borders Module Level 3 9 September 2014

A background-type method that relies on specifying sizes in a rather peculiar manner (not defined for this use case) and fallback border properties so far (eg. border: solid):

Note that, even though they never cause a scrolling mechanism, outset images may still be clipped by an ancestor or by the viewport.

This example illustrates the image being composed only as a bottom-right corner decoration:

.myClass {
    border: solid;
    border-width: 0 480px 320px 0;
    border-image: url("http://i.imgur.com/uKnMvyp.jpg") 0 100% 100% 0;
}

Applies to: All elements, except internal table elements when border-collapse: collapse

Still it can't change an <img>'s tag src (but here's a hack), instead we can decorate it:

.myClass {
    border: solid;
    border-width: 0 96px 96px 0;
    border-image: url("http://upload.wikimedia.org/wikipedia/commons/9/95/Christmas_bell_icon_1.png") 
                  0 100% 100% 0;
}
<img width="300" height="120" 
     src="http://fc03.deviantart.net/fs71/f/2012/253/b/0/merry_christmas_card_by_designworldwide-d5e9746.jpg" 
     class="myClass"

Good candidate method to be considered after standards propagate.



CSS3's element() notation working draft is worth a mention also:

Note: The element() function only reproduces the appearance of the referenced element, not the actual content and its structure.

<div id="img1"></div>

<img id="pic1" src="http://i.imgur.com/uKnMvyp.jpg" class="hide" alt="wolf">
<img id="pic2" src="http://i.imgur.com/TOUfCfL.jpg" class="hide" alt="cat">

We'll use the rendered contents of one of the two hidden images to change the image background in #img1 based on the ID Selector via CSS:

#img1 {
    width: 480px; 
    height: 320px; 
    background: -moz-element(#pic1) no-repeat;
    background-size: 100% 100%;
}

.hide {display: none}

Notes: It's experimental and only works with the -moz prefix in Firefox and only over background or background-image properties, also needs sizes specified.


Conclusions

  1. Any semantic content or structural information goes in HTML.
  2. Styling and presentational information goes in CSS.
  3. For SEO purposes, don't hide meaningful images in CSS.
  4. Background graphics are usually disabled when printing.
  5. Custom tags could be used and styled from CSS, but primitive versions of Internet Explorer do not understand](IE not styling HTML5 tags (with shiv)) without Javascript or CSS guidance.
  6. SPA's (Single Page Applications), by design, usually incorporate images in the background

Having said that, let's explore HTML tags fit for image display:

The <li> element [HTML4.01+]

Perfect usecase of the list-style-image with display: list-item method.

The <li> element, can be empty, allows flow content and it's even permitted to omit the </li> end tag.

.bulletPics > li {display: list-item}
#img1 {list-style: square inside url("http://upload.wikimedia.org/wikipedia/commons/4/4d/Nuvola_erotic.png")}
#img2 {list-style: square inside url("http://upload.wikimedia.org/wikipedia/commons/7/74/Globe_icon_2014-06-26_22-09.png")}
#img3 {list-style: square inside url("http://upload.wikimedia.org/wikipedia/commons/c/c4/Kiwi_fruit.jpg")}
<ul class="bulletPics">
    <li id="img1">movie</li>
    <li id="img2">earth</li>
    <li id="img3">kiwi</li>
</ul>

Limitations: hard to style (width: or float: might help)

The <figure> element [HTML5+]

The figure element represents some flow content, optionally with a caption, that is self-contained (like a complete sentence) and is typically referenced as a single unit from the main flow of the document.

The element is valid with no content, but is recommended to contain a <figcaption>.

The element can thus be used to annotate illustrations, diagrams, photos, code listings, etc.

Default rendering: the element is right aligned, with both left and right padding!

The <object> element [HTML4+]

To include images, authors may use the OBJECT element or the IMG element.

The data attribute is required and can have a valid MIME type as a value!

<object data="data:x-image/x,"></object>

Note: a trick to make use of the <object> tag from CSS would be to set a custom valid MimeType x-image/x followed by no data (value has no data after the required comma ,)

Default rendering: 300 x 150px, but size can be specified either in HTML or CSS.

The <SVG> tag

Needs a SVG capable browser and has a <image> element for raster images

The <canvas> element [HTML5+].

The width attribute defaults to 300, and the height attribute defaults to 150.

The <input> element with type="image"

Limitations:

... the element is expected to appear button-like to indicate that the element is a button.

which Chrome follows and renders a 4x4px empty square when no text

Partial solution, set value=" ":

<input type="image" id="img1" value=" ">

Also watch out for the upcoming <picture> element in HTML5.1, currently a working draft.

Community
  • 1
  • 1
CSᵠ
  • 10,049
  • 9
  • 41
  • 64
26

i used the empty div solution, with this CSS:

#throbber {
    background-image: url(/Content/pictures/ajax-loader.gif);
    background-repeat: no-repeat;
    width: 48px;
    height: 48px;
    min-width: 48px;
    min-height: 48px;
}

HTML:

<div id="throbber"></div>
Emmanuel Touzery
  • 9,008
  • 3
  • 65
  • 81
  • What if I want to display it inline? Adding "display: inline" gives my div dimension of 0x0... – elsurudo Feb 04 '14 at 10:28
  • 1
    @elsurudo Use display:inline-block if you want to set a width and height on an inline element – Erin Drummond Mar 19 '14 at 22:13
  • 1
    The top answer doesn't work with Firefox, so I like your answer more! And it is clear and have no css hacks. – Sergey Bogdanov May 24 '14 at 14:50
  • If you need to display more than one image, bear in mind the id field is technically supposed to be unique, so using a CSS class selector instead of the ID is ideal. – mix3d Nov 09 '16 at 15:57
  • Images of this type won't print properly if you have background graphics turned off in print settings. – posfan12 Jun 01 '18 at 11:13
15

I found a better way than the proposed solutions, but it does use the background-image indeed. Compliant method (cannot confirm for IE6) Credits: http://www.kryogenix.org/code/browser/lir/

<img src="pathTo/myImage.jpg"/>

The CSS:

img[src*="pathTo/myImage.jpg"] {

    background-image: url("mynewimg.jpg"); /* lets say 20x20 */
    width: 20px;

    display:inline-block;
    padding: 20px 0 0 0;
    height: 0px !important;

    /* for IE 5.5's bad box model */
    height /**/:20px;
}

The old image is not seen and the new is seen as expected.


The following neat solution only works for webkit

img[src*="pathTo/myImage.jpg"] {

    /* note :) */
    content:'';
    display:inline-block;

    width: 20px;
    height: 20px;
    background-image: url("mynewimg.jpg"); /* lets say 20x20 */

}
EricG
  • 3,788
  • 1
  • 23
  • 34
  • This is a neat trick, but is it really standards compliant? The [W3C page](http://www.w3.org/TR/CSS21/generate.html#propdef-content) says the `content` property only applies to the `:before` and `:after` pseudo classes. Also, if you have to support IE7 or earlier, I think `content` support is non-existent. Still, very tempting. – jatrim Jun 01 '12 at 18:15
  • You are right, I just found a more compliant method. Updating my post! Now vote me up ;) Haha. – EricG Jun 04 '12 at 08:38
  • The updated approach is definitely better than the one relying on content. Thanks for including the original link. That was insightful. You'll note that @RobAu's answer is actually very similar to your updated version as well. – jatrim Jun 04 '12 at 15:39
  • 1
    @jatrim The `content` property applies to all elements. [http://www.w3.org/TR/css3-content/#content](http://www.w3.org/TR/css3-content/#content) – XP1 May 02 '13 at 16:32
13

Here is a very good solution -> http://css-tricks.com/replace-the-image-in-an-img-with-css/

Pro(s) and Con(s):
(+) works with vector image that have relative width/height (a thing that RobAu's answer does not handle)
(+) is cross browser (works also for IE8+)
(+) it only uses CSS. So no need to modify the img src (or if you do not have access/do not want to change the already existing img src attribute).
(-) sorry, it does use the background css attribute :)

Community
  • 1
  • 1
OviC
  • 259
  • 2
  • 7
  • 1
    Now, that's the proper solution, works for me in all browsers, thanks!! Also worth to mention I had to add: background-size: 100%; to css class in solution above to make replacement image show properly. – mikhail-t Dec 02 '14 at 20:51
13

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).

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.

It works like a charm :)

agf
  • 171,228
  • 44
  • 289
  • 238
Frank
  • 161
  • 1
  • 2
  • 5
    -1 Even though your answer isn't bad, he specifically mentions that he doesn't want to use `background*` – fresskoma Aug 11 '11 at 22:17
  • 1
    this is a trick... in my opinion tricks will be changed by browsers... and a day at morning you'll see a hell in your website :D :))) – Mahdi Jazini Nov 24 '16 at 07:45
12

No you can't set the image src attribute via CSS. The closest you can get is, as you say, background or background-image. I wouldn't recommend doing that anyway as it would be somewhat illogical.

However, there is a CSS3 solution available to you, if the browsers you're targeting are able to use it. Use content:url as described in Pacerier's answer. You can find other, cross-browser solutions in the other answers below.

Community
  • 1
  • 1
cletus
  • 616,129
  • 168
  • 910
  • 942
9

You can define 2 images in your HTML code and use display: none; to decide which one will be visible.

  • I was searching far and wide for a solution that was Web Responsive but also maintained SEO. I wanted to use media queries in CSS to change my image depending on the device used, but I wanted to keep my content in HTML. Declaring sources in CSS was a route I did not want to take, so `background-image` was not an option. I wanted `img` tags for SEO purposes. Your answer is so simple, elegant, and solves all my hurdles! bravo! Also user doesn't have to download both images. Furthermore, I can add any number of images. – Xavier Jan 25 '19 at 10:41
  • Every answer I read so far would force me to either declare my sources in my stylesheet, or use inline CSS in my markup. Neither of which I was pleased with. Messy code! – Xavier Jan 25 '19 at 10:41
4

Put several images in a "controlling" container, and change the container's class instead. In CSS, add rules to manage images' visibility depending on the container's class. This will produce the same effect as changing img src property of a a single image.

HTML:

<span id="light" class="red">
    <img class="red" src="red.png" />
    <img class="yellow" src="yellow.png" />
    <img class="green" src="green.png" />
</span>

CSS:

#light         { ... }
#light         *        { display: none; }     // all images are hidden
#light.red     .red     { display: inline; }   // show red image when #light is red
#light.yellow  .yellow  { display: inline; }   // .. or yellow
#light.green   .green   { display: inline; }   // .. or green

Note that it will preload all images, like with CSS backround-images, but unlike changing img src via JS.

Bronx
  • 747
  • 8
  • 12
4

Or you could do this which I found on the interweb thingy.

https://robau.wordpress.com/2012/04/20/override-image-src-in-css/

<img src="linkToImage.jpg" class="egg">
.egg {
  width: 100%;
  height: 0;
  padding: 0 0 200px 0;
  background-image: url(linkToImage.jpg);
  background-size: cover;
}

So effectively hiding the image and padding down the background. Oh what a hack but if you want an IMG tag with alt text and a background that can scale without using JavaScript?

In a project I'm working on now I created a hero block twig template

<div class="hero">
  <img class="image" src="{{ bgImageSrc }}"
       alt="{{ altText }}" style="background-image: url({{ bgImageSrc }});">
</div>
SherylHohman
  • 16,580
  • 17
  • 88
  • 94
Pocketninja
  • 395
  • 1
  • 12
4

Some data I would leave in HTML, but it is better to define the src in CSS:

<img alt="Test Alt text" title="Title text" class="logo">

.logo {
    content:url('../images/logo.png');
}
SherylHohman
  • 16,580
  • 17
  • 88
  • 94
Renat Gatin
  • 6,053
  • 5
  • 37
  • 58
3

Alternative way

.myClass {
background: url('/img/loading_big.gif');
}
<div class="myClass"></div>
Cody Guldner
  • 2,888
  • 1
  • 25
  • 36
Tukaz
  • 72
  • 1
  • 4
2

To reiterate a prior solution and to stress the pure CSS implementation here is my answer.

A Pure CSS solution is needed in cases where you are sourcing content from another site, and thus you have no control over the HTML that is delivered. In my case I am trying to remove branding of licensed source content so that the licencee does not have to advertise for the company they are buying the content from. Therefore, I'm removing their logo while keeping everything else. I should note that this is within my client's contract to do so.

{ /* image size is 204x30 */
     width:0;
     height:0;
     padding-left:102px;
     padding-right:102px;
     padding-top:15px;
     padding-bottom:15px;
     background-image:url(http://sthstest/Style%20Library/StThomas/images/rhn_nav_logo2.gif);
}
Daniel Byrne
  • 1,411
  • 15
  • 12
2

I know this is a really old question however no answers provide the proper reasoning for why this can never be done. While you can "do" what you are looking for you cannot do it in a valid way. In order to have a valid img tag it must have the src and alt attributes.

So any of the answers giving a way to do this with an img tag that does not use the src attribute are promoting use of invalid code.

In short: what you are looking for cannot be done legally within the structure of the syntax.

Source: W3 Validator

Geowil
  • 624
  • 1
  • 12
  • 36
2

As far as I am aware of, YOU CANNOT. CSS is about style and image's src is content.

NawaMan
  • 25,129
  • 10
  • 51
  • 77
1

If you don't want to set a background property then you can't set the src attribute of an image using only CSS.

Alternatively you can use JavaScript to do such a thing.

Guillaume Flandre
  • 8,936
  • 8
  • 46
  • 54
1

Using CSS, it can't be done. But, if you are using JQuery, something like this will do the trick:

$("img.myClass").attr("src", "http://somwhere");
Veera
  • 32,532
  • 36
  • 98
  • 137
  • actually, it can )) see the answer on this same question here: http://stackoverflow.com/questions/2182716/how-can-we-specify-src-attribute-of-img-tag-in-css/19114098#19114098 – mikhail-t Dec 02 '14 at 20:55
1

You can convert it with JS:

$('.image-class').each(function(){
    var processing = $(this).attr('src');
    $(this).parent().css({'background-image':'url('+processing+')'});
    $(this).hide();
});
Raul Martin
  • 521
  • 1
  • 6
  • 19
0

If you are trying to add an image in a button dynamically based on the context of your project, you can use the ? take to reference the source based on an outcome. Here I am using mvvm design to let my Model.Phases[0] value determine whether I want my button to be populated with images of a lightbulb on or off based on the value of the light phase.

Not sure if this helps. I'm using JqueryUI, Blueprint, and CSS. The class definition should allow you to style the button based on whatever you'd like.

    <button>                           
  <img class="@(Model.Phases[0] ? "light-on": "light-off")" src="@(Model.Phases[0] ? "~/Images/LightBulbOn.png" : "~/Images/LightBulbOff.png")"/>                             
  <img class="@(Model.Phases[0] ? "light-on": "light-off")" src="@(Model.Phases[0] ? "~/Images/LightBulbOn.png" : "~/Images/LightBulbOff.png")"/>   
  <img class="@(Model.Phases[0] ? "light-on": "light-off")" src="@(Model.Phases[0] ? "~/Images/LightBulbOn.png" : "~/Images/LightBulbOff.png")"/>     

Tschlegel
  • 9
  • 1
0

I would add this: background image could be also positioned with background-position: x y; (x horizontal y vertical). (..) My case, CSS:

(..) 
#header {
  height: 100px; 
  background-image: url(http://.../head6.jpg); 
  background-position: center; 
  background-repeat: no-repeat; 
  background-color: grey; 
  (..)
} 
(...)
JaredMcAteer
  • 21,688
  • 5
  • 49
  • 65
john
  • 1
0

HTMl Code:

<!DOCTYPE html>
<html>
     <head>
         <link type="text/css" rel="stylesheet" href="css destination" />
     </head>
     <body>
<!-- click-able pic with link -->
           <a href="site you want"> 
<!-- Take the off if you don't want click-able link -->
                <h1 id(or class)="nameOfClassorid">
                     <span>Text that is not important</span>
                </h1>
           </a>
      </body>
 </html>

Css Code:

span {
     display: none;
}
h1 id or class {
     height: of pic;
     width: of pic;
/* Only flaw (so far) read bottom */
     background-image:url(/* "image destination" */);
}
h1 id or class:hover {
/* Now the awesome part */
     background-image:url(/* 'new background!!!' */);
}

I've been studying html after school for a few days, and wanted to know how to do this. Found out the background and then put 2 and 2 together. This works 100% I checked, if not make sure you fill in necessary things!!! We need to specify height, because without it there would be nothing!!! I'll leave this basic shell you can add-on.

Example:

 <!DOCTYPE html>
 <html>
     <head>
         <link type="text/css" rel="stylesheet" href="style.css" />
     </head>
     <body>
           <a href="http:localhost"> 
                <h1>
                     <span>Text that is not important</span>
                </h1>
           </a>
     </body>
 </html>
span {
     display: none;
}
h1 {
     height: 100px;
     width: 100px;
     background-image:url("http://linuxlog.org/wp-content/uploads/2011/01/Ubuntu-Desktop-@-2011-01-11-191526-300x225.png");
}

h1:hover {
     height: 300px;
     width: 300px;
     background-image:url("http://cdn.css-tricks.com/images/ads/wufoo-600x600-red.png");
}

P.S. Yes I am a Linux user ;)

0

Any method based on background or background-image is likely to fail when user prints the document with "print background colors and images" disabled. Which is unfortunately typical browser's default.

The only print-friendly and cross-browser compatible method here is the one proposed by Bronx.

Simon Rozman
  • 308
  • 3
  • 8
-1

Just use HTML5 :)

<picture>
    <source srcset="smaller.jpg" media="(max-width: 768px)">
    <source srcset="default.jpg">
    <img srcset="default.jpg" alt="My default image">
</picture>
Max
  • 608
  • 1
  • 7
  • 23
  • The OP is specifically looking to clean up their HTML markup with a CSS solution. This answer would only further clutter the markup. – webaholik Nov 04 '19 at 20:59