Adding classes to input tags as a matter of course
I felt like sharing a practice that I've been doing for a while now when marking up form elements.
I always assign a class to every input that is the same to the input's type.
<input
type="text"
class="text" />
<input
type="checkbox"
class="checkbox" />
<input
type="radio"
class="radio" />
<input
type="button"
class="button" />
For input types that would be similar in presentation, I double up:
<input
type="submit"
class="submit button" />
<input
type="password"
class="password text" />
It's not uncommon for a project to require specified padding, width, and border colors for text inputs. I don't want to target all input tags, as it could have some unintended consequences for elements I don't want changed. So this practice has helped me greatly. Its html file size impact is miniscule, and it's also easy to remember, since the type value is always the class value.
Attribute selectors vs. class names
Attribute selectors almost remove the need for me to do this, but not quite. By attribute selectors, I mean the following:
input[type="text"] { border:1px solid #000; }
... in which the value of the 'type' attribute is used instead of a class or id.
The main reason attribute selectors don't do the trick is that IE6 doesn't support them. And though I can be persuaded to let a little IE6 wonkiness slip through for some parts of web site projects, forms are where I draw the line. After all, forms are how get feedback and money from customers - why screw with that?
The secondary reason can be found from the password input example above. I want password inputs to inherit the same presentational treatment as text inputs. Using the class names defined above lets me do that.
For me, this practice has proven pretty effective. Your mileage may vary, but I'd love to hear any other tips you have in mind.
See also:
- Eric Meyer's Formal Wierdness
- Roger Johansson's Why styling form controls with CSS is problematic