htmlcssbackground-image

Fit background image to div


I have a background image in the following div, but the image gets cut off:

 <div style='text-align:center;background-image: url(/media/img_1_bg.jpg);background-repeat:no-repeat;width:450px;height:900px;' id="mainpage" align="center">

Is there a way to show the background image without cutting it off?


Solution

  • You can achieve this with the background-size property, which is now supported by most browsers.

    To scale the background image to fit inside the div:

    background-size: contain;
    

    To scale the background image to cover the whole div:

    background-size: cover;
    

    JSFiddle example or runnable snippet:

    #imagecontainer {
      background: url("http://3.bp.blogspot.com/_EqZzf-l7OCg/TNmdtcyGBZI/AAAAAAAAAD8/KD5Y23c24go/s1600/homer-simpson-1280x1024.jpg") no-repeat;
      width: 100px;
      height: 200px;
      border: 1px solid;
      background-size: contain;
    }
    <div id="imagecontainer"></div>

    There also exists a filter for IE 5.5+ support, as well as vendor prefixes for some older browsers.