Ampix0
Ampix0

Reputation: 135

How to make a CSS rollover image? (sprite)

I'm just trying to use this little trick I saw in one of my web design magazines to make a little image rollover but I'm having just a small bit of trouble. My attempt was a terrible fail lol. I just want to see the top half (42px tall) and then the bottom half on rollover (-42px obviously)

width is also 42px. Could someone write something up to make that happen? image: http://img826.imageshack.us/img826/6568/homebi.png

Upvotes: 3

Views: 4995

Answers (3)

Matt Ball
Matt Ball

Reputation: 359876

It's all about the initial (non-:hover) and final (:hover) values of background-position.

#test {
    height: 42px;
    width: 42px;
    background-image: url(http://img826.imageshack.us/img826/6568/homebi.png);
    background-repeat: no-repeat;
    background-color: transparent;
    background-position: top;  /* <-- key step #1 */
}
#test:hover {
    background-position: bottom; /* <-- key step #2 */
}

Demo


As per your comment re: wrapping the <div> with an anchor (<a>), here's what to do:

  1. Swap the <div> out for a <span>. This is because valid children of anchors must be inline elements
  2. But inline-displayed elements won't behave accept dimensions! So, fix this new problem with one additional CSS property: display: inline-block on the span.

Demo 2

Upvotes: 3

Rocket Ronnie
Rocket Ronnie

Reputation: 1116

Heres the bare bones for an image rollover.

the css

.rollover{display:block; height:42px; width:42px; background:url(http://img826.imageshack.us/img826/6568/homebi.png) top;}
.rollover:hover{background-position:bottom;}
.rollover span{display:none}

The html

<a href="#" class="rollover"><span>Home</span></a>

The important part is the background position, which on the buttons normal state is set to 'top', when you rollover the background postion is 'bottom'.

Assuming your image which contains both button states is 84px high this will work fine.

Upvotes: 0

Lucius
Lucius

Reputation: 963

Try this:

<style type="text/css">
.menu {
}
.menu a {
    float: left;
    display: inline;
    width: 42px;
    height: 42px;
    text-decoration: none;
}
.menu a span {
    display: block;
    overflow: hidden;
    height: 0;
}
.menu .home {
    background: transparent url(http://img826.imageshack.us/img826/6568/homebi.png) 0 0 no-repeat;
}
.menu .link:hover {
    background-position: 0 -42px;
}
</style>

<div class="menu">
    <a href="#" title="Home" class="link home"><span>Home</span></a>
</div>

Upvotes: 2

Related Questions