Style an HTML form input with CSS and jQuery

Posted in HTML and CSS and Javascript -

It's possible with CSS to style a particular form input type without having to assign a class to each one with the special style. For example you may want to add a margin before radio buttons in a form but not all the other input elements. Unfortunately this doesn't work in Internert Explorer 6 (which still has about 25% market share as at the writing of this post) but there is a way around this using Javascript. In this post I'll look at both the CSS way of doing this and then also using the jQuery Javascript library.

Of course it's quite possible the user has Javascript disabled, or an even older version of IE which doesn't support jQuery, so it's always a good idea to make sure the styling of your form still looks OK in IE 6 without Javascript enabled. The Javascript added styling then just adds a nice presentational touch.

The CSS way

Using the example in the opening paragraph, where you might want to style radio buttons in the form with a left margin, you could do something like this:

HTML:

<div>
  <input type="radio" name="foo" value="Yes" /> Yes
  <input type="radio" name="foo" value="No" /> No
  <input type="radio" name="foo" value="Maybe" /> Maybe
</div>

CSS:

input[type=radio] {
  margin-left: 20px;
}

This will work for any input type, so you could do any of these and more:

input[type=text] {
  ... css properties here ...
}
input[type=password] {
  ... css properties here ...
}
input[type=checkbox] {
  ... css properties here ...
}
input[type=submit] {
  ... css properties here ...
}
input[type=button] {
  ... css properties here ...
}

The jQuery way

To do the same as the radio button CSS styling above with jQuery, you would do this:

$(document).ready(function() { 
  $("input[@type=radio]").css("margin-left", "20px");
}

Styling the first one differently

As an added bonus we'll also look at how to style the first element differently. In my radio button example, all the radio buttons will have a left margin of 20px. This makes the first radio button too far over off the left margin in the form I was creating so I decided to make the left margin 10px for the first one. This can be achieved with the :first-child selector, and can again be done with CSS and then with jQuery to fix IE 6.

CSS:

input[type=radio]:first-child  {
    margin-left: 10px;
}

jQuery:

$(document).ready(function() {
  $("input[@type=radio]:first-child").css("margin-left", "10px");
}

Conclusion

Using this method of styling a particular input type means you don't need to assign a special class to each and every radio button, text box, checkbox etc that you want to style differently and can control it entirely with a CSS stylesheet. Because Internet Explorer 6 does not support this part of the CSS standard it can be worked around by using Javascript, in my examples using the jQuery library.



Related posts:


Comments