Is it possible to set the equivalent of a src attribute of an img tag in CSS?

后端 未结 25 2148
借酒劲吻你
借酒劲吻你 2020-11-22 09:30

Is it possible to set the src attribute value in CSS? At present, what I am doing is:


相关标签:
25条回答
  • 2020-11-22 10:16

    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; 
      (..)
    } 
    (...)
    
    0 讨论(0)
  • 2020-11-22 10:17

    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.

    0 讨论(0)
  • 2020-11-22 10:19

    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>
    
    0 讨论(0)
  • 2020-11-22 10:20

    Alternative way

    .myClass {
    background: url('/img/loading_big.gif');
    }
    
    <div class="myClass"></div>
    
    0 讨论(0)
  • 2020-11-22 10:21

    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.

    0 讨论(0)
  • 2020-11-22 10:21

    You can convert it with JS:

    $('.image-class').each(function(){
        var processing = $(this).attr('src');
        $(this).parent().css({'background-image':'url('+processing+')'});
        $(this).hide();
    });
    
    0 讨论(0)
提交回复
热议问题