445

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?

Purag
  • 16,611
  • 4
  • 51
  • 72
Rajeev
  • 42,191
  • 76
  • 179
  • 280

7 Answers7

870

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.

Community
  • 1
  • 1
grc
  • 21,645
  • 4
  • 39
  • 63
170

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

Sertage
  • 2,795
  • 1
  • 17
  • 23
26

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">
hojjat.mi
  • 1,168
  • 13
  • 20
11
background-position-x: center;
background-position-y: center;
Abhijeet1520
  • 113
  • 4
  • 6
9

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

Christian
  • 91
  • 1
  • 1
  • 1
    Link to a highly voted answer that talks about this solution in more detail: https://stackoverflow.com/questions/600743/how-to-get-div-height-to-auto-adjust-to-background-size and shows you how to calculate the `padding-top`. – John Lee May 01 '19 at 16:57
2

try any of the following,

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

.container{
    background-size: 100%;
}
Codemaker
  • 7,952
  • 3
  • 61
  • 53
0

Alternative:

background-size: auto 100%;
Marcel
  • 2,512
  • 2
  • 21
  • 39