Resize a div element to its background image size

前端 未结 6 648
忘了有多久
忘了有多久 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条回答
  •  梦毁少年i
    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:

    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);
    
    $('')
        .attr('src', imgSrc)
        .on('load', function() {
            img.width(this.width);
            img.height(this.height);
        });
    

    JSFiddle Demo #2

提交回复
热议问题