drewd423
drewd423

Reputation: 351

Move a CSS sprite within a div?

What I'm trying to do is have a sprite as a background for my links. Then when it hovers it changes to a different colored sprite. The code below accomplished that.

The problem is that the sprites are directly over/behind the link text. Is there a way to position where the sprite is shown in relation to the text?

If I change background-position it just changes which pixels are used for the sprite, not the actual position of the sprite. Thanks in advance!

HTML

<a class="sprite-link" href="#">Link Text</a>

CSS

a:hover {
color: black;
}

.sprite-link {
background: url(spriteurl.png) no-repeat;
background-position: 0px 0px;
width: 165px;
height: 45px;
display: block;
}

.sprite-link:hover {
background: url(spriteurl.png) no-repeat;
background-position: 0px -45px;
width: 165px;
height: 45px;
}

Upvotes: 1

Views: 1079

Answers (3)

Robert Byrne
Robert Byrne

Reputation: 560

What you probably want to do is use a separate span inside the a tag, and put the background on that.

HTML

<a class="sprite-link">
    <span></span>
    Link Text
</a>

CSS

a:hover {
    color: black;
}

.sprite-link > span {
    background: url(spriteurl.png) no-repeat;
    background-position: 0px 0px;
    width: 165px;
    height: 45px;
    display: inline-block;
}

.sprite-link:hover > span {
    background: url(spriteurl.png) no-repeat;
    background-position: 0px -45px;
}

Upvotes: 1

leoMestizo
leoMestizo

Reputation: 1499

You can use the ::after pseudo-element to achieve that...

Check the Fiddle.

I don't have the sprite, but imagine that the square in the example is it.

CSS

.sprite-link::after {
    content: "";
    padding: 10px;
    background: red;
    width: 165px;
    height: 45px;
    display: block;
}

.sprite-link:hover::after {
    width: 165px;
    height: 45px;
    background: black;
}

Upvotes: 1

Adam Jenkins
Adam Jenkins

Reputation: 55792

Use an absolutely positioned pseudo element and put the sprite inside the pseudo element.

For instance (see fiddle):

a { position: relative; padding-right: 30px; display: inline-block;}
a:before { content:""; border: 1px solid #000; display: inline-block; position: absolute; width: 20px; height: 20px; right:0; }

http://jsfiddle.net/XJZfC/

Upvotes: 0

Related Questions