CSS3 Button Maker

Avatar of Chris Coyier
Chris Coyier on

Drag things, pick colors, make a nice class for your buttons… introducing the Button Maker.

Boy, that’s a nice button right there.

I’m saying “CSS3”, because these make use of gradients, shadows, and rounded corners which contribute greatly to their button-ness. In older browers that don’t support these properties, the fallback is solid-color background, no shadows, and square corners. Not a big deal.

I hope this is painfully obvious, but to use this Button Maker thing, you just adjust the settings until you have a nice looking button, then press the button and it will give you the CSS. Copy and paste at your leisure. Now you can use the class name “button” on HTML elements to make them look like buttons. The CSS isn’t formatted real pretty. If someone has an idea on how to make that better, please do let me know.

The super-awesome empowering concept…

…in regards to how the Button Maker preview works.

It’s easy to change the CSS of an element on-the-fly with JavaScript. But how can we change the :hover state? The answer is that we can’t really, at least not really easily. We could attach a mouseenter event that would apply some new CSS that would override the old, and a mouseleave event that would put it back. That’s a lot of overhead for something so relatively small. It gets even more complicated if we wanted to control the :active state as well.

This Button Maker shows you a live working version of the button you create, complete with :hover and :active states. It is done without attaching any JavaScript events to the button itself. So how is it done? I did it with a technique I ripped off from Doug Neiner who presented it (as small part of a totally different application) at jQConf.

OK OK I’ll get on with it. The idea is to append a <style> element into the <head> which overrides the existing CSS (in-document CSS automatically overrides linked CSS for selectors with the same specificity value). Then when something changes, you literally rip the whole style tag out, and replace it.

Appending a new style:

$("head").append("<style type='text/css'></style>");

Text variable where the CSS will be kept. Keep this text up to date when options change.

var cssText = "";

Use the replaceWith() function to rip out existing style element and apply a new one:

$("style").replaceWith("<style type='text/css'>" + cssText + "</style>");

The ripping-out part is important. Originally I tried putting an ID on the style element and replacing the content within it on the fly. It did replace the content, but those changes were not reflected on the page. Apparently in order to force the browser to re-render with the new CSS, you have to literally remove it and put it back.

Take it, shake it

I’ll provide the source for the thing in case you want to run it locally for whatever reason. Or even better, because you want to make it cooler. If you do, please share.

View Demo   Download Files