Cross-Browser Rounded Buttons with CSS3 and jQuery

Published April 22, 2010 by Rob Glazebrook.

So here’s the scenario: I was tasked with replacing several dozen Photoshop-generated rounded buttons for a larger site with an HTML/CSS/JS equivalent. Prior, any time anyone wanted to change text on a button (and it seemed to happen often), a graphic designer had to fire up Photoshop, modify a file, adjust for size, output an image, and pass that file off to the person building the page. It was an involved process for something that should have been simple.

So let’s make it simple!

Right away I knew that I wanted to present as simple a solution for the developer as I could. I didn’t want to force them to use tons of extra markup in their HTML to pull this trick off. This was a piece of cake in modern browsers, as you’ll see in a moment. Unfortunately, this site also has a large IE user base, so I needed to account for less-modern browsers as well.

Border-Radius for Those Who Can

I decided I wanted to use border-radius for the rounded buttons for any browsers that could support it. I also decided that I wanted to create a single class, “button,” for any buttons, and it should work more-or-less the same on anchor tags, button tags, and “submit-type input tags.

In short, my HTML should be as simple as this:

<a href="link.html" class="button">A Button!</a>
<button class="button">Also A Button</button>
<input type="submit" class="button" value="Das Button" />

Input and button tags are admittedly tricky, as I’ve mentioned elsewhere. For this exercise we’ll ignore most of that and not worry about pixel-perfect results. Really, really close is good enough for me on this one.

My CSS for those happy modern browsers looks like this:

.button {
	display: inline-block;
	line-height: 1;
	padding: 7px 10px;
	text-decoration: none;
	font-weight: bold;
	color: #fff;
	background-color: #39c;
	-moz-border-radius: 5px;
	-webkit-border-radius: 5px;
	-khtml-border-radius: 5px;
	border-radius: 5px;
}
input.button, button.button {
	border: 0px none;
}

The display: inline-block makes our button behave like a block-level element (width, height, padding and the rest), while still staying “in line”. Our border-radius is set at the bottom: 5px, all around. We use vendor-prefixed rules first, for Mozilla, Webkit, and Khtml browsers. Then we finish with the “standard” border-radius rule, which is currently supported by Opera 10.5. We also have a separate rule to remove the default border on input and button tags. The rest is just text and color styling.

And just like that, we have nice rounded buttons that work in Safari, Chrome, Firefox and even the latest version of Opera! So who missed the party bus? Our old friend Internet Explorer, of course (and Opera browsers older than two months, as well). The client wasn’t comfortable giving those users square buttons, so I had to do something, and step one of that something is being able to tell which browsers can’t handle border-radius.

Sniff the Diff

This is where that test for border-radius support that I built last week suddenly comes in handy. I simply include a small jQuery function, run the test, and I can now tell whether or not the browser supports border-radius (vendor prefixed or otherwise). If you missed my article last week, I’d be sure to check that out before going any further.

With the help of my $.support.borderRadius object, I can now write some jQuery to treat those browsers that don’t support border-radius differently.

Modify the DOM

There’s no good way to fake rounded corners in Internet Explorer without resorting to images. However, that doesn’t mean we’re stuck with creating a one-size-fits-all button image and dealing with inflexibility. Really, the only part of the button we’re worried about changing is the borders. So let’s just worry about them!

We’re going to use jQuery to create a structure that looks like this:

<div class="buttonwrap">
	<div class="tl"></div>
	<div class="tr"></div>
	<a href="link.html" class="button">Our Button</a>
	<div class="bl"></div>
	<div class="br"></div>
</div>

The buttonwrap div acts as a container for the rest of our elements, and will be relative positioned (but not moved) to turn it into a positioned parent, letting us move objects around inside it. The four corner divs are then absolutely positioned on top of our button and moved to the four corners (“tl” for top-left and so on).

Here’s the jQuery that gets it done:

jQuery(function() {
	jQuery.support.borderRadius = false;
	jQuery.each(['BorderRadius','MozBorderRadius','WebkitBorderRadius','OBorderRadius','KhtmlBorderRadius'], function() {
		if(document.body.style[this] !== undefined) jQuery.support.borderRadius = true;
		return (!jQuery.support.borderRadius);
	});
});
$(function() {
	if(!$.support.borderRadius) {
		$('.button').each(function() {
			$(this).wrap('<div class="buttonwrap"></div>')
			.before('<div class="corner tl"></div><div class="corner tr"></div>')
			.after('<div class="corner bl"></div><div class="corner br"></div>');
		});
	}
});

If the browser doesn’t support border-radius, we wrap our buttons in the buttonwrap div, then insert our four corner divs. Admittedly, we could have put all the corners in a row, but I like the idea of putting them in the same order they’ll appear visually. And sure, it’s five extra divs in our DOM… but they’re not in our HTML. I’m comfortable with that trade-off in this situation.

Now we need just two more pieces: the CSS to position everything properly, and the image that will let us fake our corners. Let’s deal with the image first.

One Image to Round Them All

You’ll be amazed at how simple this turned out to be (at least, I was!). We only need one teeny tiny image to round all four of our corners.

In my situation, I was dealing with dozens of buttons, some of different colors, but all on a white background. Because of that, I realized what I needed was a transparent PNG: white on the outside “background” area, and transparent on the inside to let my CSS button background color show through. And because my corners were all rounded the same amount, what I really needed in each corner was a quarter of a circle.

So what I did was open up Photoshop and create a 10px by 10px image. Then I gave it a white background, used the elliptical marquee tool to draw a circle in the center, and then deleted the center out (no feathering, but with anti-aliasing).

If you only had a single button color but multiple background colors, I’d still approach it the same basic way. I’d simply “select inverse” after creating my circle, delete the outside instead of the inside, and proceed the same.

Once I saved the image as a 24-bit PNG, my total file size was 182 bytes. If I were using a fancier image program like Fireworks, I probably could have gotten the image size even smaller. And admittedly, if you want the transparent PNG to work in IE6, you’ll need to use a PNG fix of some sort. But that’s outside the scope of this particular article. Google will assist in this one.

Now, using the power of CSS background positioning, I can show just a quarter of that image in each of my corners. Here’s my final IE-friendly CSS:

.buttonwrap {
	display: inline-block;
	position: relative;
	zoom: 1;
	*display: inline;
}
.corner {
	position: absolute;
	width: 5px;
	height: 5px;
	background: transparent url(images/corner.png) no-repeat 0 0;
}
.tl { top: 0; left: 0; background-position: left top; }
.tr { top: 0; right: 0; background-position: right top; }
.bl { bottom: 0; left: 0; background-position: left bottom; }
.br { bottom: 0; right: 0; background-position: right bottom; }

Note: The “zoom” and “*display” rules above are a necessary hack that causes IE7 to mimic the inline-block property (which it does not implement correctly).

So that’s it! Here’s a working example for you to try out.

Limitations

I’ll admit it: this solution isn’t perfect. Just pretty darn convenient for my situation. Some limitations include:

  • IE6 requires a PNG fix, as I mentioned earlier.
  • You’re stuck with either one button color, or one background color, per image. Additional classes and images could expand this, though.
  • Corners are all the same radii.
  • It’d be tougher (though not impossible) with a border on the button.
  • It hasn’t made me coffee (yet).

However, I expect this will be useful to someone else. I’ve already found two uses for it since I wrote the original code!

117 Responses

  1. http://p90x3.weebly.com (reply)

    If you really want to get in shape and get healthy, taking muscle building vitamins is one
    of the best moves you can do. Anabolic Preparing food
    evaluation with regard to Dave Ruel’s muscle mass building cookery book have been introduced along Anabolic – Cooking101.
    You can workout as intensely as you like, eat all the food you can possibly handle, take as
    many supplements as you like but unless you get enough rest you’ll be severely limiting your potential to build a lot of muscle.
    In the end, you have to decide why you want to to be muscle
    building.

    My weblog – p90x3 (http://p90x3.weebly.com)

  2. Joshua Bowar (reply)

    I just like thee helpful infco you provide on yur articles.
    I’ll bookmark your weblog and check once more right here regularly.

    I am moderately sute I will be informed a lot of new stuff right right here!
    Best of luck for the next!

  3. google.ca (reply)

    Good post. I learn something totally new and challenging on sites I stumbleupon on a daily basis.
    It will always be exciting to read articles
    from other authors and practice something from their websites.

    My web site; family lawyers etobicoke (google.ca)

  4. Morgan (reply)

    Your Ьack аgain and decrease entire body iin ƿarticular will neeԁ special attention. ӏf үou hace any issues,
    yoou ϲan discuss them witɦ your doctor.
    Ѕhe has tߋ stick to precautions wɦiϲh aare approved Ьy physicians.

  5. Sybil (reply)

    I really like your blog.. very nice colors & theme.
    Did you makle this website yourself or did you hire someone to do it forr you?
    Pllz reply as I’m looking to construct my own blog and would like to know where u got this from.
    thanks

  6. Stefanie (reply)

    Fantastic web site. Lots of helpful info here. I’m sending
    it to several friends ans additionally sharing in delicious.
    And of course, thank yoou in your effort!

  7. Lorene (reply)

    For most up-to-date news you have to visit world-wide-web and on the web I found this website as a most excellent web
    site for most up-to-date updates.

  8. eventool.se (reply)

    The weather in the UK last year. The inflows
    from large foreign investors have increased over the last few months,
    and cost riad marrakech nashira several thousand pounds.
    To make the tour an easier one, we hoofer a comfortable travelling experience by arranging an expert on cemetery maintenance;
    I have to send the right signals. Heading northeast riad
    marrakech nashira around Cap Blanc, the marina at Bizerte has been closed for some time.

    My web site atv quad marrakech airport code; eventool.se,

  9. cord blood donation (reply)

    As much as you try, the fact of the matter is, we still
    do not know why Sudden Infant Death Syndrome (SIDS) occurs.

    However, much to my surprise, our family’s social worker decided against it.
    When getting prepared to dress your baby, you have to consider comfort and their skin.

  10. Meir Ezra success (reply)

    This lack of know-how makes it quite simple for environmental alarmists to
    make use of melting Arctic ice and pin the blame on it on weather transform due to a man-made increase in CO2 fuel.
    David: I simply wish that anybody on the market is having
    the most effective day time actually. The material which you
    required can be easily discover around the particular spot and may
    be store in exact same location once again.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>