with Imagination: by Dustin Diaz

./with Imagination

A JavaScript, CSS, XHTML web log focusing on usability and accessibility by Dustin Diaz

Styling inputs

Sunday, December 18th, 2005

Although there is no easy way to style input elements in a graceful and managable way, I’m hoping with the following JavaScript function we can ease this process. I know some of you are already thinking - ick, JavaScript overlapping with my styles? Well, I figure at the least, users who don’t have JavaScript will experience many other fall backs than just losing the styling of their input elements. And even that being said, only the IE users will actually be seeing this drawback.

The problem when styling input’s

Addressing the problem is fairly obivous. In HTML, there are several tag names that differentiate from each other and are easy to style uniquely from each other. However input elements can vary from a text box, radio button, and checkbox…which doesn’t make for easily styling. If we wanted to style input, we’d have to style all three types! Yuck.

Styling with Attribute Selectors

If all browsers supported attribute selectors, we could easily do the following:

styling inputs with attribute selectors

input[type='text'] { font:bold 0.8em 'courier new',courier,monospace; }
input[type='radio'] { margin:0 20px; }
input[type='checkbox'] { border:2px solid red; }

Appending className’s to our input’s

Since not all browsers support attribute selectors, we can simply use className’s instead. Although clever and smart, it can get tedious real fast. Thus, the CSS would then become this:

styling inputs with attribute selectors

input.text { font:bold 0.8em 'courier new',courier,monospace; }
input.radio { margin:0 20px; }
input.checkbox { border:2px solid red; }

And then we would have to manually add all those className’s to our html documents.

Use JavaScript to automate the process

In a situation of Thanks but no thanks, we can opt out of manually adding a className to every input element and do it with JavaScript. This function is fairly straight-forward and simple.

Function appendInputTypeClasses

function appendInputTypeClasses() {
	if ( !document.getElementsByTagName )
	return;
var inputs = document.getElementsByTagName('input');
var inputLen = inputs.length;
	for ( i=0;i<inputLen;i++ ) {
		if ( inputs[i].getAttribute('type') )
		inputs[i].className += ' '+inputs[i].getAttribute('type');
	}
}

What this function does is basically adds a className of whatever type of input it is. So if it’s type is ‘text’, then it’s className will also have ‘text’! Neat eh?

And just to be safe…

We can keep our attribute selectors as a “progressive enhancement” and our final CSS will look like this:

enhanced CSS for styling inputs

input[type='text'],input.text { font:bold 0.8em 'courier new',courier,monospace; }
input[type='radio'],input.radio { margin:0 20px; }
input[type='checkbox'],input.checkbox { border:2px solid red; }

Todays question and book information

DOM Scripting

The winner of today’s contest will receive a copy of DOM Scripting by Jeremy Keith

Come up with a make-believe Band (Music Group). Name it. Come up with an album title, and list 5 tracks from the album.

Please remember to put your answers encapsulated within a <blockquote> element, and the regular discussion as normal.

20 Responses to “Styling inputs”

  1. Justin Perkins

    Hey! This is a slightly modified version of an old article! I don’t blame you though, I can’t believe you’re doing this every day, and giving a book away everyday to boot! I sure hope you’re getting money from them ads to pay for this, seems like it would get quite expensive.

  2. Lea

    Sonik and the Hedgehogs
    Farewell, My Porcupine

    Golden Ring Things
    Fast Enough For Ya
    B-blue
    El Juego
    Broken Dreams

  3. Dustin Diaz

    @Justin: Shhhh! People will find out ;) lol.
    I figured since I improved it sometime in the last few months, I would just put up an article.

  4. Lea

    Eep, my ordered list styling didn’t show up. It should be

    - Golden Ring Things
    - Fast Enough For Ya
    - B-blue
    - El Juego
    - Broken Dreams

  5. Elliot Swan

    Interesting idea (sounds a little familiar, too Though I’m with Justin, I don’t blame you. After all, you did change some things, and you are giving away free books ).

    Name: Styling Inputs

    Album title: After JAck’s eXperience [AJAX]

    Tracks:

    1) Developer in hell [ode to IE]

    2) When all else fails

    3) Mixing flavors

    4) H*ck

    5) http://Www.hatever.happened 2 1.5?

  6. Henrique Costa Pereira

    What you think about this solution: Button Replacement ( http://www.revolucao.etc.br/archives/button-replacement/ ) Or you can analise the example ( http://www.revolucao.etc.br/artigos/button/index.htm ).
    If someone have an solution for Safari or Knoqueror contact me!!!!

  7. Nate Cavanaugh

    Great article. I am really digging this methodology, as well as your awesome function :)

    As for the band:

    Kisses Like A Car Crash

    1. Your Name Is Hydrogen
    2. The Suicide Dictionary (Your Tears, My Collar)
    3. Sunshine Calculator
    4. Tearing The Pieces
    5. Countdown To Escapism

    Wow that was pathetically emo ;)

  8. tobto

    My fun:
    onblur=”this.style.backgroundColor=’#eee’;”
    onfocus=”this.style.backgroundColor=’#efe’;”

  9. Derek

    Band: Above Standards
    Album: Delimited
    Tracks:

    Ex-HTML: A romantic ballad for a long-lost markup language.
    Closing Tags: Acoustic song about leaving things open, specifically pictures and images. (of the mind, of course)
    Really Simple Song: Five liner repetitive song about the world today.
    Screw It, I’m Hacking IE: Rock opera addressing those who give up when tough situations come.
    Fisher Price Fonts: Written for the lead guitarists’ Web 2.0-obsessed 6 year old daughter. Verse 2 includes the line: “and her cute 16 point blue writin’

  10. Jérôme Lacroix

    BAND:
    The Borders!

    ALBUM:
    CSS Greatest hits!

    TRACKS:

    1. Touch me!
    (…Touch me, i want to feel your BODY, your first div next to mine…)

    2. Hack me do
    (…Hack, Hack me do, i hate standards as you, i’ll always be blue, so please please, hack me do… )

    3. Like a Div
    (…Like a div, float for the very first time… )

    4. We are family
    (… we are family, arial, verdana are with me… )

    5. (I Can’t Get No) Absolute Position
    (… I can’t get no absolute position. ‘Cause I try and I try and I try and I try …)

  11. Sammy

    First, I like the JS/CSS technique… but, wouldn’t (I haven’t tested it) it cause a flash of styles?… e.g. unstyled elements in MSIE, then a flash as they become “re-styled”?

    As for my band:

    Artist: The Pipe (Dream) Developers
    Album: Rolling my IEyes@you

    Track 1: No Event Registered for “Mouse Up on my Div’s” a the Scroll Bar.
    Track 2: Select On Top, Like it or Not!
    Track 3: Hoping for Closure, this Summer, no Christmas, no Q1 2006, no Q3 2006…
    Track 4: The 5 year hiatus (Wishing we could turn back time) (Hard Sell - Where did our love go version)
    Track 5: Been Living Without You so long…, It’s time to move on.

  12. Pig Pen » Styling Inputs from Dustin Diaz - its an adventure

    [...] under: Standards — nortypig @ 10:23 am Styling Inputs from Dustin Diaz looks good. [...]

  13. Umpty Dumpty

    Artist: the Bumps

    Album Title: Stink Foot

    Track 1: Regular Fit
    Track 2: Al Bundy’s dream
    Track 3: Size 8
    Track 4: Dirty bootz
    Track 5: Shoegazer

  14. Pig Pen - its an adventure » Blog Archive » Styling Inputs from Dustin Diaz

    [...] The Year 2005 Feed Icons » Styling Inputs from Dustin Diaz Styling Inputs from Dustin Diaz looks good. This entry was posted [...]

  15. And the Winners are…

    [...] ntually went on to becoming a sourcerer using a twig as a wand and saving his village. 6) Styling inputs Come up with a make-believe band. Name it. An [...]

  16. Angel

    Nice solution.
    I find, however, that it does not works in InternetExplorer if I put the combined

    input[type='checkbox'],input.checkbox

    only works with the single

    input.checkbox

    Any experiences or ideas?

  17. Dustin Diaz

    You need to separate them into separate rules. Eg:
    input.checkbox { }
    input[type='checkbox'] { }

  18. Gatsu

    I am french, and in a forum (forum.hardware.fr) some people wanted to replace checkbox by an image.
    I think, it’s the only way to have a styled checkbox.

    That’s why i have made a script, that replace all checkbox by images.
    The checkbox is replaced by an image, and the image is like a checkbox.
    When you click on the associated label , it works very well :D

    My script works into firefox 1.5 (and 1.x), Internet Explorer 6.x, Opera 8.5x

    If some people could test the comportement in safari. Thanks

    Sorry but the page is in french :/
    http://gatsu.ftp.free.fr/html/checkboximg/ckbimg.html

  19. ALu21

    It doesn’t work on Firefox.

  20. Gatsu

    Of course it works in firefox 1.0+ under window, and i think in firefox mac also

Get "JavaScript Design Patterns"

"As a web developer, you'll already know that JavaScript™ is a powerful language, allowing you to add an impressive array of dynamic functionality to otherwise static web sites. But there is more power waiting to be unlocked--JavaScript is capable of full object-oriented capabilities, and by applying OOP principles, best practices, and design patterns to your code, you can make it more powerful, more efficient, and easier to work with alone or as part of a team."

Buy JS Design Patterns from Amazon.com Buy JS Design Patterns from Apress

All content copyright © 2003 - 2009 under the Creative Commons License.

Archives | Blog Search