1

The div that I want to apply a background on is larger than my sprite, and the part of the sprite that I want to use as the background is 100px from the top of the sprite.

How can I set the background of the div to be the part of the sprite I want, and have it be positioned to the right side of the div.

What I have: http://jsbin.com/yibesu/1/edit?html,css,output

I want the "what-i-want" background to be pushed to the right side of the div, and the rest of it be the red color.

My CSS:

div { 
  background: url('http://i.imgur.com/VBe5ey2.png') red;
  background-position: 0 -100px;
  background-repeat: no-repeat;
  width: 400px; 
  height: 200px; 
}

It's like I want the background position to be "0 -100px" and pushed to the right of the div. The sprite's width is smaller than the div. Is this possible? Or do I need to just rip the part out of the sprite and have it be it's own image? Thanks!

Ian Davis
  • 19,091
  • 30
  • 85
  • 133
  • possible duplicate of [Clip/Crop background-image with CSS](http://stackoverflow.com/questions/7777159/clip-crop-background-image-with-css) – Dai Jun 18 '14 at 21:34

2 Answers2

1

You're close. The only thing you need to do is use background-position to align it to the right. The new css is as follows:

div { 
  background: url('http://i.imgur.com/VBe5ey2.png') red;
  background-position: right -100px;
  background-repeat: no-repeat;
  width: 400px; 
  height: 200px; 
}

I tested it with Firefox, Chrome and IE11 and all seemed to work ok.

entropic
  • 1,683
  • 14
  • 27
0

When I want to do this I will position my sprite to the right side of the sprites PNG, and with enough vertical space below it to ensure the next sprite in the graphic won't be visible at the bottom of the div.

In CSS I would define the background image's horizontal position as right:

div { 
  background: red url('sprite.png') right -100px no-repeat;
}

Here's an edited verion of your JSBin: http://jsbin.com/kohivibu/1/edit

Jonathan Nicol
  • 3,158
  • 1
  • 21
  • 22