Resize a div element to its background image size

前端 未结 6 607
忘了有多久
忘了有多久 2021-01-04 11:24

Is it possible to make a

adapt to its background image? I mean to maintain the proportions width and height.

Clarification:

相关标签:
6条回答
  • 2021-01-04 11:49

    Ok, my solution is a little bit tricky, but it works. It's a javascript and involve jquery as you wanted. The idea is to create a new image, add it to the DOM, waits till it loads and gets its dimensions. After that the new image is removed and the width and height are applied to the original img tag. Here is a js fiddle demonstrating the workaround http://jsfiddle.net/krasimir/bH5JZ/5/

    And here is the code:

    $(document).ready(function() {
        var image = $("#image");
        var imageurl = image.css("background-image").replace(/url/, '').replace(/\(/, '').replace(/\)/, '');
        var body = $("body");
    
        var newimage = $('<img src="' + imageurl + '" />');
        newimage.css("display", "none");
        body.append(newimage);
        newimage.on("load", function() {
            var w = $(this).width();
            var h = $(this).height();
            image.css("width", w);
            image.css("height", h);
            newimage.remove();
        });
    });
    

    And the css:

    #image {
        margin: 0px auto;
        background-image:url('http://www.w3.org/html/logo/downloads/HTML5_Logo_512.png');
        background-repeat:no-repeat;
        background-size:100%;
        background-color:yellow;
    }
    
    0 讨论(0)
  • 2021-01-04 11:57

    The easiest thing to do that doesn't need any javascript is to set your image as the background image and then make a .gif or a .png of the same size that you set as an overlay image in that div. That transparent .png or .gif will size the div. Transparent .png or .gif are only a couple of KB and your page will complete loading faster than with javascript.

    <!DOCTYPE html>
    <html>
        <head>
        <style>
        div {
            background-image:url("myImage.jpg");
            background-size:100% auto;
            }
        </style>
        </head>
        <body>
            <div><img alt="" src="myOverlay.png"></div>
        </body>
    </html>
    
    0 讨论(0)
  • 2021-01-04 11:58

    By using CSS, It's not possible to change an element's dimension according to its background-image size, to achieve this, you should use JavaScript:

    HTML:

    <div id="image"></div>
    

    JavaScript:

    var 
        img = document.getElementById('image'),
        style = img.currentStyle || window.getComputedStyle(img, false),
        imgSrc = style.backgroundImage.slice(4, -1),
        image = new Image();
    
    image.src = imgSrc;
    img.style.width = image.width + 'px';
    img.style.height = image.height + 'px';
    

    JSFiddle Demo


    Update: jQuery version

    Here is the the jQuery version.

    var
        img = $('#image'),
        imgSrc = img.css('background-image').slice(4, -1);
    
    $('<img />')
        .attr('src', imgSrc)
        .on('load', function() {
            img.width(this.width);
            img.height(this.height);
        });
    

    JSFiddle Demo #2

    0 讨论(0)
  • 2021-01-04 11:58

    Maybe using javascript, you can get the url to the image:

    var img = document.getElementById('image').style.backgroundImage; 
    var width = img.clientWidth;
    var height = img.clientHeight;
    document.getElemetById('image').style.width = width;
    document.getElemetById('image').style.height = height;
    

    I strongly suspect you cannot do this exclusively with stylesheets.

    0 讨论(0)
  • 2021-01-04 12:06

    No it is NOT possible to adapt a div to it's background image.

    Because it is 'senseless'

    This is how:

    A div's size is determined by its "content", or if its dimensions are SPECIFICALLY set. Since the background-image does not fall into any of these categories, you can see that it's impossible.

    What you CAN do is this:

    HTML

    <div class="image-controlled">
      <img>...</img>
      <div class="content">...</div>
    </div>
    

    CSS

     .image-controlled {
       position: relative; 
       overflow: hidden <-- optional, if you want to cut off .content which overflows the image boundaries
     }
     .content {
       position: absolute;
       top: 0; left: 0; <-- position of the content as it should be (normally)
     }
    

    The div will now be the size of the image, and the .content will be shown over it.


    Also note that the .content div can come above or below the <img> in order of appearance, but the effect would be the same. But, if you apply a position property on the img element too, then you'll need to set the z-index of .content greater than that of <img>

    0 讨论(0)
  • 2021-01-04 12:07

    Yes. We can make background image adapt to its div, like make it responsive too.

    Tips for a responsive background image: background-size:cover
    -set bg image to background-size cover
    -in css the padding set to percentage both top and bottom
    -make the bg image no repeat

    see this link: https://jsfiddle.net/beljems/dtxLjmdv/

    0 讨论(0)
提交回复
热议问题