Style an HTML input field by name and type

Posted in HTML and CSS -

If a form has a number of input fields they can each be styled using the element's "name" and/or "type" property as well as the "id" property. This is useful if you don't want to have to assign ids to all of your form elements as well as names.

How it works

It is possible to match elements based on one of its attribute settings with CSS. For example, to match all radio buttons and apply some style to them and not to other input types you can do this:

input[type=radio] {
    /* some style here for radio buttons but not other input types */
}

This works for other HTML element attributes, such as a[rel=...]

Text Input Example

The first CSS example shows setting the default width for all text inputs to 150px and then setting the width for the "phone_number" text input to 100px:

input[type=text] {
    width: 150px;
}
input[name=phone_number] {
    width: 100px;
}

Select Example

The second CSS example below shows setting the default width for select boxes to 200px (whereas by default they will be the width of the widest option) and then for the "area_code" drop down box (following the phone number theme from the last example) to 50px:

select {
    width: 150px;
}
select[name=area_code] {
    width: 75px;
}

IE6 does not support these selectors

If the website you are working on still has a reasonable percentage of Internet Explorer 6 visitors then be aware that these selectors do not work in IE6. This shouldn't normally present too many issues: it will simply mean that whatever styling is applied with these selectors won't appear in IE6. If it's critical to the design of a page, and IE6 is important, then use an ID for the element and style it that way instead.



Related posts:


Comments