why should CSS Spirte image in negative values

199 views Asked by At

I have one doubt do we need to give negative values for CSS Sprite images, i am using a vertical spirte image. Can i give postive values also in this if yes will it work on responsive versions too.

background:url(images/test.png) 0 232px/ 100% auto;
1

There are 1 answers

2
Justinas On

Yes, you can put negative values to background-position: x y. Question is... Why you want to place Sprite in not visible area?


Why background-position is negative?

When you specify background-position: 0 0 it means that sprite image top-left corner is in top-left corner of element. Now that you want to show more inner view of image you have to move your sprite in desired direction according to element. So background-position-x mean you are moving sprite top-left corner to the right from where your element top-left corner is.

Visualization:

$(document).ready(function() {
    setInterval(function () {
        setTimeout(function () {
            $('.position').text('Left: 50px; Top: 50px;');
            $('.window, .wrapper').css({'background-position': '50px 50px'});
        }, 0);

        setTimeout(function () {
            $('.position').text('Left: -50px; Top: -50px;');
            $('.window, .wrapper').css({'background-position': '-50px -50px'});
        }, 1000);

        setTimeout(function () {
            $('.position').text('Left: -50px; Top: 0px;');
            $('.window, .wrapper').css({'background-position': '-50px 0px'});
        }, 2000);

        setTimeout(function () {
            $('.position').text('Left: 50px; Top: 0px;');
            $('.window, .wrapper').css({'background-position': '50px 0px'});
        }, 3000);

        setTimeout(function () {
            $('.position').text('Left: 0px; Top: 0px;');
            $('.window, .wrapper').css({'background-position': '0px 0px'});
        }, 4000);
    }, 5000);
});
.wrapper {
  width: 400px;
  height: 200px;
  position: relative;
  background: url('http://lorempixel.com/400/200/technics/9/') no-repeat;
}
.wrapper:after {
  content: '';
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  z-index: 1;
  background-color: white;
  opacity: 0.7;
}
.window {
  position: relative;
  z-index: 5;
  width: 50px;
  height: 50px;
  border-right: 3px dotted #888;
  border-bottom: 3px dotted #888;
  background: url('http://lorempixel.com/400/200/technics/9/') no-repeat;
}
.position {
  background-color: white;
  right: 0;
  bottom: 0;
  position: absolute;
  display: inline-block;
  padding: 3px 10px;
}
.position:before {
  content: 'Position: ';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Real image:
<br/>

<img src="http://lorempixel.com/400/200/technics/9/" />
<hr/>

<div class="wrapper">
  <div class="window"></div>
  <div class="position"></div>
</div>