tom 0

I want to apply a background image to a link <a> so that it's styled like a button.

Do I have to convert it to from an inline to block element (display:block) in order to set the height and size or is there another workaround?

4 answers

BPartch 342
1
point
This was chosen as the best answer
<a href="URL"> <div class="button">Iam a Link</div></a>

Is invalid HTML. You cannot place block level elements inside inline elements.

Try:

`<a class="button" href="#" title="#">Link text</a>`

a.button{
  display:block;
  background: url(image.jpg);
  width: 100px;
  height: 30px;
}
Answered almost 7 years ago by BPartch
  • Thanks - I have another related question though :p! What's the best way of getting the text vertically centered in relation to the image? tom almost 7 years ago
2
points

To vertically center a line of text within an "image" just set the line-height to the height of the button.

Answered almost 7 years ago by Anthony Lemmer
Saiyan 113
0
points

maybe you can just use this:

<a href="URL"><img src="IMAGE" height="100" width="100" alt="Click Me"/></a>

so the whole image is a link and you can size it like you want to

Edit: You could also place a div with a background image into the link like this.

<a href="URL"> <div class="button">Iam a Link</div></a>

and this is the CSS:

.button{
        background: url(image.jpg);
        height: 100px;
        width: 400px;
}
Answered almost 7 years ago by Saiyan
Armada 0
0
points

Why not use a real button with a javascript redirect?

<button type="button" onclick="window.location='http://www.google.com/'">Click Me!</button>

Or without javascript

<form action="http://www.google.com/">
    <input type="submit" value="Click Me!" />
</form>
Answered almost 7 years ago by Armada
  • I would avoid this as you can do it with no need for JS + you never know when a user might have JavaScript disabled. BPartch almost 7 years ago
  • You mean by using a form with the address as the action? Armada almost 7 years ago