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:


This post was ported from an old host and CMS, so many comments were lost. Below are the comments that I found were most helpful regarding this post that I salvaged. Some links or attributions may not be working correctly.


Ace Calhoon said:
I’ve not used attribute selectors much for essentially the reason you list as primary above (no IE6 support, and a lot of people use that browser). But your secondary reason seems a bit odd.
Couldn’t you write the selector as:
input[type=”text”], input[type=”password”] { /* shared CSS */}
input[type=”password”] { /* password specific CSS */ }
?

This article was ported from an older CMS, and comments were purposefully lost in the migration. If some were found most relevant, I pasted them to the bottom of that post. No new comments are accepted on these older articles.

Comments are closed.