2

Currently, if my browser is half the monitor's size it will shrink the background to fit the width, cutting off the height and the bottom. I'd like it to instead, keep the height, filling the whole page, and keeping the aspect ratio but just centering the photo and cutting off the sides of the photo, my current CSS is just

body{
    background-image: url("/background1.jpg");
    background-size: 100%;
    background-repeat:no-repeat;
    display: compact;
}

Any help on how to do this would be great, thank you

Fuledbyramen
  • 185
  • 1
  • 3
  • 16

3 Answers3

2

Adding background-size: cover should do the clipping and keeping aspect ratio.

Adding background-position: center; will keep the image in the centre.

(replace rule for div and place it to your body - I used div here for the sample code only)

See running sample below

div {
  background-image: url("http://placehold.it/1000/1000");
  /* Resizes image to fill div; retains aspect ratio. */ 
  background-size: cover;  
  background-repeat: no-repeat;
  background-position: center;
  min-height: 2000px;
}
<div>
  Lorem Ipsum
</div>
blurfus
  • 13,485
  • 8
  • 55
  • 61
1
background-size: cover; 

Should do what you need. Handles cropping / scaling pretty elegantly.

phynam
  • 467
  • 2
  • 12
1

use background-size: auto 100%; in that rule:

body {
    background: url("/background1.jpg") center center no-repeat;
    background-size: auto 100%;
}

The first parameter (in background-size) is the width, the second the height of the image. If there is only one parameter (as in your rule), the browser will assume it's the width and set the height to auto. My version should give you the full height and adjust the width automatically (and center the image)

Johannes
  • 64,305
  • 18
  • 73
  • 130