Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

Assigning Background Image to a Div Issue

I specified the height of a div to 198px, the same height as the source image itself. Yet the full image is not displaying, and some of it is cut off.

http://codepen.io/bluehabit/pen/yyjOKq

.hero {
  background: url('http://s4.postimg.org/qodjah8dp/banner_cat.png') no-repeat;
  width: 100%;
  height: 198px;
  background-size: cover;
  padding-left: 225px;
}

The full image should look like this.

alt text

2 Answers

Luke DePass
Luke DePass
6,843 Points

Hi Chris,

The issue is that background-size: cover, ensures that your background image is the same size or GREATER than the containing element. So with some images, you will see exactly what you are seeing with your issue.

What you actually want is to ensure that your whole image is seen - so the image should be as large as it can be, but never exceed the containing elements height and width. That way your nice rounded corners will not be cut off.

To do that you would use background-size with the value "contain" instead of "cover"

So your code would look like this:

.hero {
  background: url('http://s4.postimg.org/qodjah8dp/banner_cat.png') no-repeat;
  width: 100%;
  height: 198px;
  background-size: contain;
  padding-left: 225px;
}

I hope this helps. Here is some documentation on MDN: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Scaling_background_images#Special_values.3A_.22contain.22_and_.22cover.22

Luke DePass The issue with changing the background-size value to cover is it will cause the div image to shrink when you scale the browser window down. Here is a quick mock up I made comparing cover vs contain for background-size on the image.

alt text

The curious thing is on the live hosted site, the image is working exactly as I intend it too, yet the CSS code is the exact same and using background-size: cover. It shows enough of the image height to reveal the rounded corners as you can see here http://cssdojo.net/cat/

.header{
  background: url('../images/banner-cat.png') no-repeat;
  width: 100%;
  height: 198px;
  background-size: cover;
  padding-left: 225px;
}