Grow your CSS skills. Land your dream job.

Is there a way to automatically re-size div according to the size of its background image?

  • # June 12, 2013 at 3:52 pm

    I have a div with a background image that is changed with Jquery. I want the div to resize itself when according to the size of its background image. If the background image is small than it shrinks to that size. Is this possible in any way?

    # June 12, 2013 at 3:53 pm

    If you can define the bg image sizes as variables in the JS then I suppose so but it’s not something that would be detected automatically.

    Certainly not by CSS.

    # June 12, 2013 at 4:07 pm

    Or making the background image one specific width but not height so it wont stretch. will work too.

    # June 12, 2013 at 4:10 pm

    With javascript you can load the background image as


    var bg=new Image;
    bg.src='path/x.jpg'
    $(bg).load(function() {
    var bgW=bg.width;
    var bgH =bg.height;
    $('div.box').width(bgW).height(bgH);
    })

    Or you could just do another way around, using background size to fit the div’s dimensions (background-size:contain);

    # June 12, 2013 at 4:29 pm

    Nevermind with this question. I found an alternative. Thank you guys anyways.

Viewing 5 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".