Image Sprites

Image sprites are used a technique to load multiple images within a single image and therefore only a single web request and then specifying an area of the image which is known as a sprite.

 

An image sprite will have a number of smaller images within specific areas, such as this example:

 

 

Specific image sections are picked out using co-ordinates.

 

In the above image and following example, the height for each sprite within the image is defined as 95px;

 

Left 0px, Top 0px, represents the top left corner.

 

The width of the first image within the sprite is 77px.

 

Therefore to select just the first image, an area is defined as being 0px from the left of the image with a width of 77px, and having a background image with left top coordinates of 0 0.

 

The next sprite is then defined to start at 78px from the left with a width of 98px, and having a background image with left top coordinates of -77px 0.

 

*Note: the left coordinate is now being defined as a negative number, this is because the new coordinate we want to see is to the right of the initial image and since the background-position is set using top left coordinates we need to specify negative values relative to the top left. Thus -77px is equivalent to saying right 77px. Similarly sprites further down the image use negative values, and therefore -101px represents the sprite 101px from the top of the image. Confusing, yes, but that's the way it is!

 

The third sprite is then defined to start at 177px from the left with a width of 78px, and having a background image with left top coordinates of -178px 0.

 

Hover effects can be added by defining the lower set of sprites simply placed at the lower coordinate -101px.

 

<!DOCTYPE html>
<html>
	<head>
		<title>My Document Title</title>
		<style>
			#icons {position:relative;}
			#icons li {list-style:none; position:absolute; top:0;}
			#icons li, #icons a {height:95px; display:block;}

			#css3 {left:0px; width:77px;}
			#css3 {background:url('./sprites.jpg') 0 0;}
			#css3 a:hover {background:url('./sprites.jpg') 0 -101px;}

			#php {left:78px; width:98px;}
			#php {background:url('./sprites.jpg') -77px 0;}
			#php a:hover {background:url('./sprites.jpg') -77px -101px;}

			#html5 {left:177px; width:78px;}
			#html5 {background:url('./sprites.jpg') -178px 0;}
			#html5 a:hover {background:url('./sprites.jpg') -178px -101px;}
		</style>
	</head>
	<body>
		<div>
			<ul id="icons">
				<li id="css3"><a href="https://www.css3.com" target="_blank"></a></li>
				<li id="php"><a href="https://www.php.net" target="_blank"></a></li>
				<li id="html5"><a href="https://www.html5rocks.com" target="_blank"></a></li>
			</ul>
		</div>
	</body>
</html>

Save & refresh browser:

iframe source*

Leave a Reply