Misha Moroshko
Misha Moroshko

Reputation: 171399

How to create click-able CSS sprite with <a> rather than Javascript?

Here is an example of click-able CSS sprite implemented with Javascript:

Live demo here.

HTML:

<div></div>

CSS:

div {
    width: 100px;
    height: 100px;
    background-image: url(http://perfectwebtutorials.com/wp-content/uploads/2011/03/spritecss.png);
    background-position: -300px -100px;
}
div:hover {
    background-position: -100px -100px;
}

JS:

$(function() {
    $('div').click(function() {
        window.location = "http://google.com";
    });
});

Is that possible to achieve the same without Javascript ?

(The only way I can think of is to use <a href="...">, but how ?)

Upvotes: 0

Views: 1070

Answers (5)

Blowsie
Blowsie

Reputation: 40555

Simply change it a <a> and add display:block or similar to your css.

Example here.

http://jsfiddle.net/blowsie/t629m/11/

Upvotes: 1

sandeep
sandeep

Reputation: 92813

@misha,check the like http://jsfiddle.net/sandeep/t629m/7/

the main thing is that you have to display:block in <a> tag

because <a> is an inline element example:

a {
    width: 100px;
    height: 100px;
    background-image: url(http://perfectwebtutorials.com/wp-content/uploads/2011/03/spritecss.png);
    background-position: -300px -100px;
    display:block;
}

Upvotes: 2

thirtydot
thirtydot

Reputation: 228202

You asked your question in a convoluted way, but the answer is simple:

  • Change the div to an a.
  • Apply display: block to the a.

See: http://jsfiddle.net/65HdK/

<a href="http://google.com/"></a>

a{
    width: 100px;
    height: 100px;
    background-image: url(http://perfectwebtutorials.com/wp-content/uploads/2011/03/spritecss.png);
    background-position: -300px -100px;

    display: block
}
a:hover {
    background-position: -100px -100px;
}

Upvotes: 4

rzetterberg
rzetterberg

Reputation: 10268

<a href="http://google.com"><div></div></a>

Seems to be working fine. Live demo: http://jsfiddle.net/vuZz4/

Upvotes: 1

Andy E
Andy E

Reputation: 344675

With an <a> element, give it a href and display: inline-block, along with all the other CSS properties you have set.

a {
    display: inline-block;
    width: 100px;
    height: 100px;
    background-image: url(http://perfectwebtutorials.com/wp-content/uploads/2011/03/spritecss.png);
    background-position: -300px -100px;
}
a:hover {
    background-position: -100px -100px;
}

Working demo: http://jsfiddle.net/t629m/13/

Upvotes: 4

Related Questions