Styling form elements with CSS attribute selectors

The type of attribute selector we're going to use is called exact match attribute selector and has the form E[attribute="value"], where E is the element to match. We want to:

  1. give a border and a dimension to text fields
  2. give a dimension and a different background image to each label element.

Let's see how we can actually achieve this goal with attribute selectors.

form input[type="text"] {
  width: 150px;
  border: 1px solid #ccc;

form label[for="first-name"],
form label[for="last-name"],
form label[for="email"],
form label[for="subject"] {
 width: 140px;
 padding-right: 10px;
 display: block;

form label[for="first-name"],
form label[for="last-name"] {
 background: transparent url("../img/name.png") no-repeat 100% 100%;

form label[for="email"] {
 background: transparent url("../img/email.png") no-repeat 100% 100%;

We've specified a right padding on label elements which is equal to the width of the background images. By doing so, we avoid any possible overlapping of text and background images when the user resizes the text.

However, in Internet Explorer 7 the background images won't be displayed at all, because this browser doesn't allow this kind of styling on label elements. To avoid this problem, simply wrap the label elements with other elements (such as spans) and assign the styles of labels to them. Fortunately, this problem has been fixed in Internet Explorer 8.

Leave a Reply

Note: Only a member of this blog may post a comment.