My CSS Sprite here
The problem is 开发者_如何转开发that the image changes position even when the empty area to the right of links is hovered over with mouse..what I want is the image position to change ONLY when mouse is over those texts ie "Link1", "Link2", etc.
What do I need to change in my code ?
You need to shrinkwrap the elements.
http://jsfiddle.net/xkRcN/8/
Bad HTML! Bad bad HTML! Shrinkwrapping is of course the correct solution, but surely it'll be good to use valid HTML at the same time?
Using the general sibling selector, this code will work without causing dozens of validation errors at the same time.
HTML:
<div class="container">
<a href="#" class="sprite sp_ID1">Link 1</a>
<a href="#" class="sprite sp_ID2">Link 2</a>
<a href="#" class="sprite sp_ID3">Link 3</a>
<a href="#" class="sprite sp_ID4">Link 4</a>
<a href="#" class="sprite sp_ID5">Link 5</a>
<a href="#" class="sprite sp_ID6">Link 6</a>
<div class="sp_ID0"></div>
</div>
CSS:
.sprite {
display: block;
margin-bottom: 5px;
float: left; /* These two lines are where the shrinkwrapping occurs */
clear: both;
color: white;
}
.container, .sp_ID0 {
width: 600px;
height: 203px;
}
.sp_ID0 {
background-image: url(http://farm5.static.flickr.com/4106/5064283850_fc6b5fac15_b.jpg);
background-repeat: no-repeat;
}
.container {
position:relative;
}
.sp_ID0 {
z-index: -2;
position: absolute;
top: 0px;
left: 0px;
display: block;
}
.sp_ID1:hover ~ .sp_ID0 { background-position: 0px -203px; }
.sp_ID2:hover ~ .sp_ID0 { background-position: 0px -406px; }
.sp_ID3:hover ~ .sp_ID0 { background-position: 0px -609px; }
.sp_ID4:hover ~ .sp_ID0 { background-position: 0px -812px; }
.sp_ID5:hover ~ .sp_ID0 { background-position: 0px -203px; }
.sp_ID6:hover ~ .sp_ID0 { background-position: 0px -406px; }
精彩评论