Salman Arshad
Salman Arshad

Reputation: 272146

Display one icon from CSS sprite in a larger div

I have a sprite image which contains various 40x40px icons:

Sprite

Then I have a div that is much larger than this sprite. I want to show the play icon (left, top = 120, 0) in the middle of that div. I do not want to show the whole sprite.

How can I do this using CSS without editing the HTML markup or the image?

.play {
  position: absolute;
  left: 10%;
  right: 10%;
  top: 10%;
  bottom: 10%;
  background-color: rgba(255, 255, 0, .5);
  background-image: url(https://i.sstatic.net/pxuWK.png);
  background-position: -120px 0;
}
<div class="play" title="Play Button Hitbox"></div>

Upvotes: 1

Views: 602

Answers (2)

CreMedian
CreMedian

Reputation: 803

You are going to have the problem of dealing with the overflow since the div is larger.

My suggestion would be to create a :before or :after element to put the play icon within, then position it relative to its parent so you can hide the overflow.

The code to do this is as follows:

.play {
  position: absolute;
  left: 10%;
  right: 10%;
  top: 10%;
  bottom: 10%;
  background-color: rgba(255, 255, 0, .5);
}
.play:after {
  content: "";
  position: absolute;
  background-image: url(https://i.sstatic.net/pxuWK.png);
  background-position: -120px 0;
  width: 40px;
  height: 40px;
  left: 50%;
  margin-left: -20px;
  top: 50%;
  margin-top: -20px;
}
<div class="play" title="Play Button Hitbox"></div>

http://jsfiddle.net/dzg9h2r6/1/

Upvotes: 0

Heidar
Heidar

Reputation: 689

You can use pseudo element to apply the specific part you want to, here is the code:

   .play {
        position: absolute;
        left: 10%;
        right: 10%;
        top: 10%;
        bottom: 10%;
        background-color: rgba(255, 255, 0, .5);
        background-position: -120px 0;
    }
    .play:before {
        display:inline-block;
        content:'';
        width: 35px; /*width of icon*/
        height: 44px; /*height of icon*/
        background-position-x: -43px; /*x position of icon relative to sprite image*/
        background-position-y: 4px; /*y position of icon relative to sprite image*/
        background-image: url(https://i.sstatic.net/pxuWK.png);
    }

Upvotes: 1

Related Questions