Wednesday, March 11, 2015

CSS Sprites - offset the background

Method 1 (preferred):

<html>
<head>
<style>
.myul {
  position: relative;
}

.myli {
  position: absolute;
  list-style: none;
  width: 52px;
  height: 52px;
  background: url('mysprite2.gif') no-repeat;
  display: block;
  top: 0px;
}

.myli:hover {
  background-position-y: -51px;
}

#myli1 {
  background-position-x: 0px;
  left: 0px;
}

#myli2 {
  background-position-x: -51px;
  left: 54px;
}

#myli3 {
  background-position-x: -102px;
  left: 108px;
}

#myli4 {
  background-position-x: -153px;
  left: 162px;
}
</style>
</head>
<body>

<ul class="myul">
  <li id="myli1" class="myli"></li>
  <li id="myli2" class="myli"></li>
  <li id="myli3" class="myli"></li>
  <li id="myli4" class="myli"></li>
</ul>

</body>
</html>

Method 2:

<html>
<head>
<style>
.myul {
  position: relative;
  width: 400px;
  height: 200px;
  background: transparent url('mysprite.jpg') no-repeat;
  padding: 0px;
}

.myli {
  position: absolute;
  list-style: none;
  width: 100px;
  height: 200px;
  top: 0px;
  display: block;
}

#myli1 {
  left: 0px;
}

#myli2 {
  left: 100px;
}

#myli3 {
  left: 200px;
}

#myli4 {
  left: 300px;
}

#myli1:hover {
  background: transparent url('mysprite.jpg') 0px -200px no-repeat;
  opacity: 0.8;
}

#myli2:hover {
  background: transparent url('mysprite.jpg') -100px -200px no-repeat;
  opacity: 0.8;
}

#myli3:hover {
  background: transparent url('mysprite.jpg') -200px -200px no-repeat;
  opacity: 0.8;
}

#myli4:hover {
  background: transparent url('mysprite.jpg') -200px -200px no-repeat;
  opacity: 0.8;
}

</style>
</head>
<body>

<ul class="myul">
  <li id="myli1" class="myli"></li>
  <li id="myli2" class="myli"></li>
  <li id="myli3" class="myli"></li>
  <li id="myli4" class="myli"></li>
</ul>

<img src="mysprite.jpg" />

</body>
</html>

No comments: