Easy auto-width HTML button with 1 background image

Posted on

Here’s a super simple technique to create a button of variable width in HTML/CSS.

I started here and then stripped it down to only 2 HTML elements, your A and an EM.

This technique uses one background image for the button.

First, create a button image that is about 2x as long as any button would ever be on your site.

Like so:

The rest is in the CSS comments…

<a href="#" class="button"><em>CLICK ME!!!</em></a>

.button{
border:none;
background:none;
padding:0;
margin:0;
width:auto;
height:31px;
overflow:visible;
text-align:center;
display:inline-block;
white-space:nowrap;

/* Here's the magic sauce
padding left is the space between the left edge of your button and your text
background is set to left top
*/

padding-left:22px;
background:url(../images/largeBtn.png) no-repeat 0 0;
}

.button em{
height:31px;
display:block;
margin:0;
color:#fff;
font-style:normal;
line-height:33px;

/* Here's the magic sauce
margin right is the radius of your rounded corner if you have one (so pngs don't show through behind)
padding right is the space between the right edge of your button and your text
background is set to right top
*/

margin-right:-3px;
padding-right:22px;
background:url(../images/largeBtn.png) no-repeat 100% 0;

}

One thought on “Easy auto-width HTML button with 1 background image

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*