Toward Better Buttons

I see this a lot:

<input type="submit" class="button" value="Save Changes" />

Because the <input /> element can represent many things other than a button—and because many browsers still don't support attribute selectors, such as input[type=button]—the author has added class="button" for the sole purpose of giving the stylesheet something to match on.

May I suggest a better way?

<button type="submit">Save Changes</button>

Now our stylesheet can simply use the selector button, and we don't have to add any extra classes to our markup. Overall, it makes for cleaner, more concise, and more semantically descriptive code.

That one isn't so bad, but this one is:

<input type="image" src="button.gif" alt="Save Changes" />

This is technically valid under XHTML 1.0 Transitional, but not under XHTML 1.0 Strict, and it's a bad idea in either case.

Why? Because it couples semantics with presentation, and that's exactly the sort of thing CSS exists to prevent. If the client later decides to replace button.gif with newbutton.jpg—or wants to change all image buttons to text buttons—you'll have to edit every page to make the change.

Instead, use this markup:

<button type="submit" class="submit">Save Changes</button>

...and use your favorite CSS image replacement technique to progressively enhance the document for graphical user agents. I typically use something like this:

button.submit {
    border: 0; /* to suppress default button styling */
    padding: 0; /* to suppress default button styling */
    background-image: url("button.gif");
    width: 128px;
    height: 24px;
    text-indent: -9999px; /* to hide the plain text */
    outline: 0; /* suppress the dotted hairline border */
}

Now you'll only have to edit one file—the stylesheet. Yes, we've re-introduced classes, but in this case it actually helps us separate concerns. You can define a base button style, and then define styles for button.submit, button.cancel, button.delete, button.help, and so on—each one pulling in the appropriate background-image and specifying the appropriate dimensions.

Comments

No comments yet.

Leave a Reply

(will not be published)
(optional)

What My Clients Say

Travis has helped us with many web development projects, and has proven himself to be very talented, professional, consistent, reliable, and thorough.

—Derrick Miller
Axis 80 Interactive