Fit background image to div

HtmlCssBackground Image

Html Problem Overview


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?

Html Solutions


Solution 1 - Html

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

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

Solution 2 - Html

If what you need is the image to have the same dimensions of the div, I think this is the most elegant solution:

background-size: 100% 100%;

If not, the answer by @grc is the most appropriated one.

Source: http://www.w3schools.com/cssref/css3_pr_background-size.asp

Solution 3 - Html

You can use this attributes:

background-size: contain;
background-repeat: no-repeat;

and you code is then like this:

 <div style="text-align:center;background-image: url(/media/img_1_bg.jpg); background-size: contain;
background-repeat: no-repeat;" id="mainpage">

Solution 4 - Html

background-position-x: center;
background-position-y: center;

Solution 5 - Html

you also use this:

background-size:contain;
height: 0;
width: 100%;
padding-top: 66,64%; 

I don't know your div-values, but let's assume you've got those.

height: auto;
max-width: 600px;

Again, those are just random numbers. It could quite hard to make the background-image (if you would want to) with a fixed width for the div, so better use max-width. And actually it isn't complicated to fill a div with an background-image, just make sure you style the parent element the right way, so the image has a place it can go into.

Chris

Solution 6 - Html

try any of the following,

background-size: contain;
background-size: cover;
background-size: 100%;

.container{
    background-size: 100%;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRajeevView Question on Stackoverflow
Solution 1 - HtmlgrcView Answer on Stackoverflow
Solution 2 - HtmlSertageView Answer on Stackoverflow
Solution 3 - Htmlhojjat.miView Answer on Stackoverflow
Solution 4 - HtmlAbhijeet1520View Answer on Stackoverflow
Solution 5 - HtmlChristianView Answer on Stackoverflow
Solution 6 - HtmlCodemakerView Answer on Stackoverflow