Search code examples
csscss-sprites

My sprite images is not showing?


This is my code, simply, I want to center the slider. But Images are not showing and I am very sure the location[image reference] is proper. So what is wrong with my code? Help me?

body {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}
.slider {
  width: 50%;
  height: 30%;
  margin: 0 auto;
}
.slider#img1 {
    background: url('../images/all-images-sprite.png') no-repeat  0 -1368px;
    background-size: cover;
    width: 300px;
    height: auto;
}
.slider#img2 {
    background: url('../images/all-images-sprite.png') no-repeat  0 -1740px;
    background-size: cover;
    width: 300px;
    height: auto;
}
.slider#img3 {
    background: url('../images/all-images-sprite.png') no-repeat  0 -1568px;
    width: 300px;
    height: auto;
}
.slider#img4 {
    background: url('../images/all-images-sprite.png') no-repeat 0 -967px;
    width: 300px;
    height: auto;
}

this is my jsfiddle


Solution

  • to keep the ratio you need to size width and height.

    from your fiddle we can start from html (window's size).

    Your mistakes: width:50% and then 300px. and then height:auto which is null when container is empty. also, the selector to use is .slider #id where #id is a child

    so the example :) https://jsfiddle.net/rdjajvuh/3/

    html,
    body {
      height: 100%;
      width: 100%;
      margin: 0;
      padding: 0;
    }
    .slider {
      width: 50%;
      height: 33vw;
      margin: 0 auto;
      border: solid;
    }
    /* demo test purpose*/
    .slider>div {/* see me */
      box-shadow:0 0 0 1px ;
      }
    .slider #img1 {
      background: url('https://s32.postimg.org/ge685yjyt/all_images_sprite.png') no-repeat 0 0;
      background-size: cover;
      width: 100%;
      height: 100%;
    }
    .slider #img2 {
      background: url('https://s32.postimg.org/ge685yjyt/all_images_sprite.png') no-repeat 0 12%;/* % because size is 50%x33vw ... */
      background-size: cover;
      width: 100%;
      height: 100%;
    }
    .slider #img3 {
      background: url('https://s32.postimg.org/ge685yjyt/all_images_sprite.png') no-repeat 0 23%;
      background-size: cover;
      width: 100%;
      height: 100%;
    }
    .slider #img4 {
      background: url('https://s32.postimg.org/ge685yjyt/all_images_sprite.png') no-repeat 0 33.65%;
      background-size: cover;
      width: 100%;
      height: 100%;
    }
    <div class="slider">
      <div id="img1"></div>
      <div id="img2"></div>
      <div id="img3"></div>
      <div id="img4"></div>
    </div>
    
    <a href="#">Previous</a>
    <a href="#">Next</a>

    for background-position since image can be any size, you can use % (run snippet in full page mode to see why). tune it to your needs