Tuesday, 23 April 2013

CSS and HTML5: background image in buttons

   


Would you like to do something like:

Or maybe you prefer it another way, like:




They look the same, don't they? However they are a bit different in the making. Let's see how...

The first way to do such thing is to use the <button> tag:
<button>
<img src="http://www.w3.org/html/logo/downloads/HTML5_Logo_32.png" />
</button>
The image is just like any text we usually put inside the tag.


Yet there's another way, which uses background-images in CSS. I personally believe that it is a better way of handling the button.
In the above examples, the first is an image (as you can see you can't click on it), while the second is live (it's an actual button you can click but that does nothing).

In order to do it the second way, we need to create a short style, like:
<style>
.btn {
height: 37px;
width: 37px;  
background-image:url('http://www.w3.org/html/logo/downloads/HTML5_Logo_32.png');
background-repeat:no-repeat;
}
</style>
And then, we need to insert our button (assigning the related class) where we want to:
<button class="btn"></button>
And that is all.

Short post, for very very busy days. See you next time!

2 comments:

  1. There's a few improvements that could be made here:

    • Add 'type=submit' to the button so it works in older browsers

    <button type="submit" class="btn"></button>

    • Add some button text for screen readers to describe what the button does

    <button type="submit" class="btn">Submit</button>

    • Use a more modern approach to image replacement:

    <button type="submit" class="btn ir">Submit</button>

    .ir {
    height: 37px;
    width: 37px;
    background:transparent url('http://www.w3.org/html/logo/downloads/HTML5_Logo_32.png') no-repeat;

    border: 0;
    overflow: hidden;
    /* IE 6/7 fallback */
    *text-indent: -9999px;
    }

    .ir:before {
    content: "";
    display: block;
    width: 0;
    height: 150%;
    }

    ReplyDelete

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.