Web dev quick tip: Style your INPUT elements by type

One thing I recently found out from looking through some example CSS: when doing web development or design, you may want to apply certain attributes to one type of input field but not another. For example,

is coded:

<input type="button" value="A Button" />

The problem therein is that you may want different borders, backgrounds or sizing attributes for your buttons, text fields, radio buttons, check boxes and password fields. Internet Explorer is an especially aggravating candidate for this, since it enforces border styles around the actual radio button itself. Safari behaves differently than other browsers as well, since it likes to enforce OS X-style control attributes.

In your CSS file or <style> tag section, you can force specific elements with attributes to take certain styles, such as this example from a recent project:

input[type="text"], input[type="password"], textarea {
border: 1px solid #aaa;
background-color: #f5f5f5;
}
input[type="text"]:focus, input[type="password"]:focus, textarea:focus {
border: 1px solid #336bc3;
background-color: #ffffff;
}
input[disabled][type="text"] {
border: 1px solid #888;
background-color: #ddd;
}
input[disabled][type="text"]:hover {
border: 1px solid #888;
background-color: #ddd;
}

In this example, text fields and textarea elements will be styled with a specific background color and border, which won’t affect other elements such as buttons.

Another neat trick I’ve learned while working on this project is the ability to put action images inside <button> elements. Instead of the <input type="button" /> tag, using the HTML 4 <button> element allows even more tricks. For example:

<button type="button"><img src="images/rss.gif" alt="" /> RSS</button>

would give something like this: