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

HTML

background-position not working

I am trying to center a background image

My HTML is <div class="container"> <div class="inner"></div> </div>

My css is .container { width: 80%; background-color: red; background-position: center; text-align: center; }

.inner { border: 1px solid; height: 160px; width: 320px; background-position: 50% 50%; background: green url("welcome-small.png") no-repeat center; }

I can't get it to work. I've tried putting background position everywhere humanly possible!!!! Any ideas???

I'm not sure why it's not working, but is there any other CSS targeting .inner after that declaration?

I've made a jfiddle here that shows that a background image can be centered like you want it.

Is the URL of the image in your CSS correct? Usually it's in another folder (like "img/???.png"), maybe that's the case here?

4 Answers

sorry - the html isn't posting.... go here http://codepen.io/anon/pen/ogPrxV

Oh, if it's the green box you're trying to center in the red box, then you'll need to add

margin: auto;

in your .inner DIV as it's not the background of the red DIV.

Thanks Ryan - No - That jsfiddle doesn't work for me either. I don't know what is wrong with it. I know that images are usually in another folder but I'm making a basic example with the image in the same folder for simplicity.

HTML is

<code> <div class="container"> <div class="inner"></div> </div> </code>

Wow!!! That works!!! Thanks so much. I've been trying to work this very simple thing out for ages!!! ;-)

You're welcome! I see the problem you had before now though.

CSS cascades, meaning that properties can be overwritten if the same property appears further down.

With your example, you were using:

background-position: 50% 50%;

and then in the next line using:

 background: green url("welcome-small.png") no-repeat center;

In this case, 'background' is the shorthand way of declaring all background properties at once, and by not declaring the position property there, you overwrote it back to default, which is 'top left' because it was further down in your declaration. (Note that 'center' is not valid as a background-position value.)