58

I have a photo type (not landscape) background image with 979px width by 1200px height. I would like to set it to float left and show 100% full image height fixed, without the need to scroll up/down (regardless of content length).

This is my CSS code, but it is not working:

img, media {
    max-width: 100%;
}

body {
    background-color: white;
    background-image: url('../images/bg-image.jpg');
    background-size: auto 100%;
    background-repeat: no-repeat;
    background-position: left top;
}
Tot Zam
  • 8,406
  • 10
  • 51
  • 76
hangee
  • 719
  • 2
  • 9
  • 12

5 Answers5

102

You can do it with the code you have, you just need to ensure that html and body are set to 100% height.

Demo: http://jsfiddle.net/kevinPHPkevin/a7eGN/

html, body {
    height:100%;
} 

body {
    background-color: white;
    background-image: url('http://www.canvaz.com/portrait/charcoal-1.jpg');
    background-size: auto 100%;
    background-repeat: no-repeat;
    background-position: left top;
}
Tot Zam
  • 8,406
  • 10
  • 51
  • 76
Kevin Lynch
  • 24,427
  • 3
  • 36
  • 37
  • 1
    Thanks. I always wondered why this was working every now and then. Now I know :D – Alexandre Bourlier Jul 26 '14 at 14:55
  • very nice ! Important fact to know or may be i have never expected this that is why i am somewhat astonish. that all the operations, you should do after setting the `background-image`. I was setting the `background-size` before and it was not working. – tech_geek Jan 10 '18 at 08:21
9
body{
    background-image: url("your_image_src");
    background-repeat: no-repeat;
    background-size: 100% 100%; 
    height: 100vh;
}

it can cover full height and width as well

6

CSS can do that with background-size: cover;

But to be more detailed and support more browsers...

Use aspect ratio like this:

 aspectRatio      = $bg.width() / $bg.height();

FIDDLE

Riskbreaker
  • 4,621
  • 1
  • 23
  • 31
3
 html, body {
    height:100%;
}

body { 
    background: url(images/bg.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
morten.c
  • 3,414
  • 5
  • 40
  • 45
him
  • 3,325
  • 3
  • 14
  • 17
0

This worked for me (though it's for reactjs & tachyons used as inline CSS)

<div className="pa2 cf vh-100-ns" style={{backgroundImage: `url(${a6})`}}> 
........
</div>

This takes in css as height: 100vh

manzim
  • 31
  • 2