Brian Breeden Brian Breeden - 1 month ago 18
CSS Question

CSS Background Image Scale to Center?

https://jsfiddle.net/2esv5wja/

css code snippet:

.imageContainer {
height: 750px;
width: 100%;
overflow: hidden !important;
}

.imageContent{
background: url('http://orig15.deviantart.net/0e45/f/2010/052/1/1/calvin_and_hobbes_2010_by_nami86.png') no-repeat center center;
background-size: 100%;
width: auto;
height: 100%;
padding-top: 3%;
padding-bottom: 3%;
min-width: 1200px;
overflow: hidden !important;
}


Is there a way to make it so when the image stops scaling, it crops to the center? That is, as it stands, it crops from the right. Can we crop from both sides evenly? If so, how is that done?

Answer

Please see the updated jsfiddle > here

You need to scale by height in order to get the crop effect you are looking for in order to do this, please see the code:

.imageContent{
    background: url('http://orig15.deviantart.net/0e45/f/2010/052/1/1/calvin_and_hobbes_2010_by_nami86.png') no-repeat center center;
    background-size: auto 100%;
  height: 500px;
  padding-top: 3%;
  padding-bottom: 3%;
}

The background size property handles the scaling which is why I have changed it to be so that the width is always auto and the height is 100%, I have then added a hard height in pixels which you can change. This creates the desired effect.