Forms pose a series of usability and accessibility challenges, many of which are made more complex when you need to build a form to fit into a small space. Tightly spaced forms can look great on paper, but they often ignore accessibility issues altogether.
A designer recently handed me a compact-form design that included the oft-seen technique of putting field names directly inside of the text fields themselves.
The typical method of marking this up is to put the field name in the value
attribute of each input
element. You would then throw in some JavaScript and server-side scripting to make sure that the user didn’t submit the form with the default values of “username” and “password.” Password fields, though, are designed to safely hide input from prying eyes, replacing each character with an asterisk or bullet. So this method prevents us from putting anything useful into the password field—and even if this were not the case, default values provide no truly accessible information about the form itself.
Figure 1: Example of a compact-form with the field names inside text fields.
In this article, we’ll create a compact form that provides a high degree of accessibility, despite its reduced size. Note that I’m not saying that tiny forms are a good idea. Rather, I’m providing a means for reconciling the space-saving aims of your client (or boss, or designer) with your desire to offer a good user experience.
Starting with accessible markup#section2
To maintain accessibility, each form element should have an associated label
that identifies that element’s purpose. Despite its compact design, there’s no reason our form can’t meet this guideline. As with any new site or page, we’ll start with plain-vanilla markup that is functionally correct and accessible and then we’ll use style sheets and JavaScript to enhance layout and functionality.
In this demonstration, we’ll use style sheets to make it look like form label
s are actually inside of the fields themselves, but they will in fact be separate elements. (Line wraps marked » —Ed.)
<form name="login" acti method="post"> <div id="username"> <label for="username-field" » class="overlabel">Username</label> <input id="username-field" type="text" » name="username" title="Username" » value="" tabindex="1" /> </div> <div id="password"> <label for="password-field" » class="overlabel">Password</label> <input id="password-field" type="password" » name="password" title="Password" » value="" tabindex="2" /> </div> <div id="submit"> <input type="submit" name="submit" » value="Login" tabindex="3" /> </div> </form>
Each label
and input
element is wrapped in a div
to provide a clean appearance when it’s viewed without a style sheet. You could wrap these in fieldset
elements instead, but in my opinion, a single field does not make a set.
We’ve given each of the label
s the class name of “overlabel.” Rather than using this class as a CSS selector, we’ll use JavaScript to locate all label
elements with this class name and apply event handlers to each of them. Using classes instead of id
s allows us to easily add functionality to sets of elements without having to keep track of specific id
s.
In addition to the label
tags, we’ve added title
attributes to each input
field to enhance usability for sighted viewers, since the label
itself will be hidden from view once the user enters information into each field.
Next, we’ll add the styles needed to overlay each label
.
form#login { position:relative; } div#username, div#password { position:relative; float:left; margin-right:3px; } input#username-field, input#password-field { width:10em; } label.overlabel { position:absolute; top:3px; left:5px; z-index:1; color:#999; }
There’s nothing surprising about the style sheet. Using absolute positioning on the label
s takes them out of the flow of the form, and since the div
s are floated to the left, the input
fields line up next to each other without any extra spacing. This works especially well for my form, where these fields lie next to each other in a horizontal arrangement. The label
elements have also been given a z-index
because they will sit in front of other field elements.
Depending on the size of your font and form fields, you may need to juggle the positioning for the label
s, but this example renders consistently across all modern browsers. We’ll use scalable units—in this case, ems—to allow users to resize the text size in their browsers and ensure that the text fields and labels grow proportionally.
Add a reusable script#section3
The label
s for each field need to be hidden when the associated field is selected, and if there is a value in either of the fields, its label
should stay hidden. This should be the case whether the page was loaded with a value in the value
attribute or if it was added by the user after the page is loaded.
We’ll be relying on JavaScript to hide the label
s, so we’re going to make a small swap in the “overlabel” class we defined. The label
s should remain visible if JavaScript is not available.
label.overlabel { color:#999; } label.overlabel-apply { position:absolute; top:3px; left:5px; z-index:1; color:#999; }
To maintain accessibility of the label
s, we will use a negative text-indent to hide the text from view, rather than setting the display
to “none.” (Line wraps marked » —Ed.)
<!-- Can't follow the JavaScript. I've left my halting start at cleanup here if it can be of any use. For sure, all have to be replaced with <i> function initOverLabels () { if (!document.getElementById) return; var labels, id, field; // Set focus and blur handlers to hide and show // labels with 'overlabel' class names. labels = document.getElementsByTagName('label'); for (var i = 0; i < labels.length; i++) { if (labels<i>.className == 'overlabel') { // Skip labels that do not have a named association // with another field. id = labels<i>.htmlFor || labels.getAttribute ('for'); if (!id || !(field = document.getElementById(id))) { continue; } // Change the applied class to hover the label // over the form field. labels.className = 'overlabel-apply'; // Hide any fields having an initial value. if (field.value !== '') { hideLabel(field.getAttribute('id'), true); } // Set handlers to show and hide labels. field.onfocus = function () { hideLabel(this.getAttribute('id'), true); }; field.onblur = function () { if (this.value === '') { hideLabel(this.getAttribute('id'), false); } }; // Handle clicks to label elements (for Safari). labels.onclick = function () { var id, field; id = this.getAttribute('for'); if (id && (field = document.getElementById(id))) { field.focus(); } }; } } };function hideLabel (field_id, hide) { var field_for; var labels = document.getElementsByTagName('label'); for (var i = 0; i < labels.length; i++) { field_for = labels<i>.htmlFor || labels. getAttribute('for'); if (field_for == field_id) { labels.style.textIndent = (hide) ? '-1000px' : '0px'; return true; } } }window.onload = function () { setTimeout(initOverLabels, 50); }; -->
function initOverLabels () { if (!document.getElementById) return; var labels, id, field; // Set focus and blur handlers to hide and show // labels with 'overlabel' class names. labels = document.getElementsByTagName('label'); for (var i = 0; i < labels.length; i++) { if (labels<i>.className == 'overlabel') { // Skip labels that do not have a named association // with another field. id = labels<i>.htmlFor || labels<i>.getAttribute » ('for'); if (!id || !(field = document.getElementById(id))) { continue; } // Change the applied class to hover the label // over the form field. labels<i>.className = 'overlabel-apply'; // Hide any fields having an initial value. if (field.value !== '') { hideLabel(field.getAttribute('id'), true); } // Set handlers to show and hide labels. field.onfocus = function () { hideLabel(this.getAttribute('id'), true); }; field.onblur = function () { if (this.value === '') { hideLabel(this.getAttribute('id'), false); } }; // Handle clicks to label elements (for Safari). labels<i>.onclick = function () { var id, field; id = this.getAttribute('for'); if (id && (field = document.getElementById(id))) { field.focus(); } }; } } };function hideLabel (field_id, hide) { var field_for; var labels = document.getElementsByTagName('label'); for (var i = 0; i < labels.length; i++) { field_for = labels<i>.htmlFor || labels<i>. » getAttribute('for'); if (field_for == field_id) { labels<i>.style.textIndent = (hide) ? '-1000px' : » '0px'; return true; } } }window.onload = function () { setTimeout(initOverLabels, 50); };
The script looks through all of the label
s on the page for any that include the class
name “overlabel.” It locates associated fields based on the value of the label
’s for
attribute, which should match an input
tag’s id
. Our new class, “overlabel-apply”, is applied to each of these label
s. Additionally, onfocus
and onblur
event handlers are added to these input
fields that will control the text-indent of associated label
s, hiding them from view.
As mentioned above, this script works independently from the name
s and id
s of the input
fields. It identifies label
s with the class
name of “overlabel.” Just as class
can be used to apply styles to sets of elements on a page, so we use it here to add functionality to those same elements. (Hat tip to Daniel Nolan, whose Image Rollover code demonstrated this approach to me a few years ago.)
It may strike you as odd that the onload
handler uses a short timeout, but this pause allows us to accommodate browsers that offer to save login credentials for frequently-visited sites. These browsers often insert saved values into HTML forms after the page has completed loading, and a built-in pause seems to ensure that a label
won’t be left hovering on top of your saved account information if this happens.
Note that only in the last section of the initOverLabels
function do we have to provide any browser-specific code. Clicking on a label
element typically passes the cursor’s focus to the related input
field, but not so with Safari, where the label
effectively blocks the user from selecting the field. To get around this, we add an onclick
handler to the label
that simply passes the focus for us.
Summary#section4
This working example provides a clean, accessible technique for visually locating a field name inside of the field itself without tampering with the initial value. Submitting the form without touching any of the fields provides an empty set of data, rather than sending “username” and “password” to your script as values. Furthermore, we can easily add these “overlabels” to any form by adding a class
name, a little bit of CSS, and the JavaScript code provided above.
As icing on the cake, if the user visits the site without JavaScript or CSS capabilities, the form is still usable and the label
s will lie next to each field as was originally intended before your designers got involved.
Great article, Mike! Although it has some problems with the password field in FireFox 2.0
Very useful and it works great.
RE: Comment #1, What problems does it have?
In Firefox 2 (OS X), the password field isn’t rendering properly. It simply shows a password field with asterisks “********”
If you turn off JavaScript the labels remain in place over the fields causing an overtype effect. Wouldn’t it be a better solution to set the position of the labels using a JS function or even use JS to:
a. Hide the labels and…
b. Determine the text for each label, and finally…
c. Use that text as the default value for the appropriate field?
Where do you set the value of the pasword field to be “password”, and how ??
It’s a great concept, but I do agree with Sean: wouldn’t it be much easier (and probably safer) to just get the value of the associated label and set this as a default value vor hte input field? I’m not sure about using CSS and the overlay technique for this.
Great technique and works on Windows (some issues apparently on OSX) but in my opinion should designers be using this pattern to design forms in the first place? It would always be more usable to provide the label above the field if there is horizontal restriction of space, if the space is restricted vertically, use a horizontal layout. If it is a really small screen, use the first option with a scroll. Why resort to this?
Sean is right that turning off JavaScript would break this. But the proposed solution doesn’t work – you can’t present a default value in the password input (without changing it’s type).
But using this concept, you’d better add the overlabel class to the labels with Javascript.
Is there any reason you’re giving the divs their own ids? They all seem to perform the same functionality in the CSS so can’t you just use them as a container with no id and no class and reference them from within the form id, i.e. #formname div.
Sorry if I’ve missed something, it would just seem to clean up the CSS and markup a lot that way?
..and then he notices the submit div being different. But still most divs will be exactly the same and you could just override this one as necessary?
The ‘issues’ some people are having with Firefox is that it is pre-filling the password field with your saved ALA password. I’m not sure why it isn’t doing the same with the username field.
Also, a simple solution to cope with browsers that support CSS but not JavaScript is to dynamically add a class to the body such as ‘hasJS’ then prefix each CSS rule with ‘.hasJS’ so it only fires when JavaScript is available and enabled.
Why dont we just use the excellent script by Aaron Boodman? It’s nearly perfect and addresses the same issues (unobtrusive, doesnt send label value if empty, etc). And even better, since it’s 2001… so old he just archived it as “boring” 🙂
http://boring.youngpup.net/2001/labels
Paul – you’re right, the DIVs could have been given any class name, ID, or none at all. These DIVs only provide an example of how the form could be styled. Certainly, your own implementation of this technique will have different styling requirements.
Now I have to rewrite Payraise Calculator! 🙂
http://www.payraisecalculator.com
I utilized this same approach but my code was rather inefficient. Thanks for the great tip!
Seems like it’d be easier/lighter to simply parse the input in the label element instead of using a div. Doing this creates an even tighter association and saves some mark-up.
Nice topic, though. It’s good to see this sort of thing.
“¦using z-index, negative margin, & transparency, setting backgroud of input to white on blur by JS, if value is not empty
the label is unobstusive, then, and degrade more gracefully if no JS (show label as /background/).
LABEL.overlabel {
z-index: 2 ;
color: lightgray;
}
input.username {
z-index: 1 ;
background-color: transparent ;
position:relative;
left: -10em;
width:10em;
}
input.username:focus {
background-color: white ;
}
with included input into label tags (better for buggy browser for the « for » attribute) : , allow easy relative position and no div.
Thanks for the article. I think that maybe you could be interested on this:
Greenpeace presents a new website in Web 2.0 where people can give ideas to improve the next expedition to Antarctic. You can post your idea or comment and vote other s ideas The whaling fleet has left Japan, and is headed directly to the Southern Ocean. 945 whales will be killed – unless we do something to save them.
http://whales.greenpeace.org/global
Nice article. I especially liked the idea of ‘floating’ the label over the text field and the fact that labels will ‘link’ to the text field if clicked, allows a user to get at the text field that is under the floated element.
However… I have to agree with Sean Foushee in post #4. This current example fails the ‘unobtrusive JavaScript’ ideal. Should JavaScript not be available, this solution does not breakdown nicely.
Instead, I would consider using JS to add the CSS that ‘floats’ the labels, thus, if JS is not on, the design can still be user friendly. Though, this can effect the design on a whole if the small form is now 2x as long.
Cheers,
John
I like the concept, but as other commenters have said, it’s a bit shaky with the javascripts and floats. I would definitely prefer the label method. I have seen this implemented on a few sites, but the worst examples don’t replace the text values back into the fields once the user clicks off of them. For example: username appears, user clicks, clicks to another field, what was in the original field? Whoops. I’ll stick with label and input thank you. Call me old fashioned Web 2.0 🙂
I would advise using valid markup by using FIELDSET element instead of non-semantic DIV element.
Please note: FIELDSET element is required in forms in XHTML 1.0 Strict.
I am sorry for the misunderstanding, but was outraged to see that you recommend something that is not accessible. (and with the Javascript off, it wasn’t even usable at all).
I am also very sad to see that A List Apart have been ignoring semantics of XHTML (HTML) all these years. Solutions you recommend are often very bad practice of HTML development recommending non-semantic elements. This is the case with DIV used here instead of FIELDSET used properly, but there were many cases of the same style in past.
Maybe some of your authors are not keeping up to date with internet semantics, but A List Apart should at least check the semantics and other errors occuring all over the place. Otherwise we can see lot of people ending up using your solutions that are sometimes very clumsy regarding semantics. I am sure you understand this is not the best case for web standards advocacy.
Thank you.
How about this?
http://www.sitepoint.com/article/behaved-dhtml-case-study
Thanks for this useful article, it came at a perfect time. Our designer put together a login form concept that used the exact example you give. I attempted a ‘default value’ solution (the traditional method), with an extra type change on the password field. This didn’t work in IE6 so I used another method which swapped in an additional form field – but was never happy with it.
The only change I have made to your concept is to have the labels next to the fields by default, and then switch the class using the Javascript to move them over the fields.
As for using fieldsets rather than DIVs, my fields are both in a single fieldset, but I have also retained your DIVs for the exact reason you described – browser default styles will render the form much more neatly with them in.
Thanks!
Well, ALA definitely makes me sad lately 🙁
If you choose to use XHTML for your example, then please, make sure it works as XHTML. Save your example with an .xhtml extension and try to open it with Firefox or Opera. See what I mean?
Problems with your current implementation:
a) CSS won’t work. XHTML is case sensitive so none of your CSS rules will apply if document gets parsed as XHTML (e.g.served with apropriate MIME type. See http://www.w3.org/TR/CSS21/syndata.html#q6 ).
b) Javascript won’t work. “In XHTML, the script and style elements are declared as having #PCDATA content.” (http://www.w3.org/TR/xhtml1/#h-4.8 ). This means that any “&” or “<" will result in "yellow page of dead". Best way to avoid this is to keep all scripts in external files, but this is not so convenient for the example page, so you have other options: escape offending characters; wrap evertyhing in CDATA (but this will bring headache in HTML mode); or, best of all — stick to HTML4.01 I am embarassed to point to this article at ALA, but do I have a choice? So: http://lachy.id.au/log/2005/12/xhtml-beginners
There’s a “simple” form on my work site that has irked me for months now. And despite deducing your technique at a glance, brilliant me, I never once thought of this on my own.
Your article exemplifies the beauty of this site. “Why default to a value that isn’t a valid value?” Simple, excellent point. And kudos on the illustration that accompanies it–my favorite so far!
Just a couple of comments:
bq. I would advise using valid markup by using FIELDSET element instead of non-semantic DIV element.
Daniel – as used in these examples, the
with JS disabled, example is not accessible or usable anymore because of the overwritten text. this could be handled by JS applied only after CSS formatting (i.e. change the CSS via JS).
Daniel:
bq. with JS disabled, example is not accessible or usable anymore because of the overwritten text. this could be handled by JS applied only after CSS formatting (i.e. change the CSS via JS).
Absolutely – agreed.
What of the the other points I made, though? In particular, the *requirement* for a
First, I’d like to thank everyone who has been participating in the discussion.
There have been some important details brought up, especially related to the initial state of the form if JavaScript is disabled. A modification has been submitted that addresses this issue.
A couple other details were brought up related to script included within the HTML file and the omission of FIELDSET elements. I suspect that this makes easy sample for readers to download and review — one file, simple, neat.
bq. As is probably clear, when we describe a technique and provide a demo, we’re rarely recommending that you go out and put the demo itself into a production environment.
I don’t think I can put this any better than Erin did. I’m demonstrating the idea that LABELs can be used appropriately in these compact forms. If you use this in your own site, you’ll certainly make your own decisions on markup, layout, class names, etc.
Lastly, I appreciate Navneet’s comment (#7) and want to reiterate a point I made in the article. I don’t condone this sort of layout at all. But anyone who has earned a living in client services knows, there are some arguments that you just can’t win. So why not make the most of it!
You can use DIV as it is block element as well. But FIELDSET is much more correct for this purpose. IMHO, using non-semantic elements for any purposes is not way to advocate web standards.
As for the argument that FIELDSET should group similar form fields, username and password are of one group (e.g. login fields).
How would You handle an error message? (eg. The email adress entered is not valid.)
I agree that a FIELDSET could have been used in this form to wrap all of the form elements as a group. I don’t think that this would have added to the demonstration of how LABELS can be used in place of default values within INPUT tags to describe the fields.
Also note that one of my intentions was to show a vertical form layout in the absence of CSS (perhaps a handheld device). I’m confident that ALA readers will adjust this example to fit their own specific requirements.
Thank you again for your enthusiastic comments.
Thanks for a good article!
It’s a good technique, and it works well. I’ve just tested it on several mobile devices using a couple of different browsers and it degrades beautifully. It also works just fine-and-dandy with JAWS 8.0…
… that makes it pretty accessible in my book! 😉
I’m not aware of a requirement for a fieldset, but I do feel it would have been better to use it in lieu of a div in the example and in a real world implementation. One could style the fieldset element however one wishes to the best of my knowledge, to include making it so it’s not be seen at all.
Daniel – thanks for responding…
bq. You can use DIV as it is block element as well. But FIELDSET is much more correct for this purpose. IMHO, using non-semantic elements for any purposes is not way to advocate web standards.
bq. As for the argument that FIELDSET should group similar form fields, username and password are of one group (e.g. login fields).
Yes, a
And Mike Cherim is right – there is no requirement for a
I’m done now. 🙂
I think that you should add cursor:text; to the label.overlabel-apply{} because the default cursor may confuse a little the users.
You need to degrade gracefully this of course doesn’t work however I would recommend something more along the lines of:
@Barry Rader
As far as I know _type_ is a read-only property, at least in IE.
Why don’t we just position the labels off the page? ( position: absolute; left: -9999em;) that way the screen readers still read it but no one else sees it. It also shows up for everyone with css and js off ( because it doesn’t really need js)
The only JS you could use if you decide to still use default values is a clear on focus or click to get rid of the default values or validate the information.
Sorry but this solution is unnecessary and impractical.
Remeber the more code you right the more you maintain.
Just wanted to say that it is a great article. I think I read it 4-5 times now. Hopefully one day I will understand it all.
This is really good for saving space, but it can be even smaller if “Go” button is replaced with “Sign In” – this way no title raw is needed
@Sander Aarts Your right it is a problem in IE although it is visually intuitive regardless of this problem since UserName is almost always paired with a password field, I doubt too many people would get confused on this one. However, I guess I could go with backgrounds on the fields themselves and turn those off and on. If it is a requirement of a clients that is.
@Nick Morgan Clients do not always see it that way.
A really really nice one!
Great article! Very useful.
I’ve taken the suggestion here and applied to my site (thank you).
The problem I have is that IF I add
document.forms[0].elements[0].focus();
To focus the curor then the userid field does not clear the label placed inside the field. If I don’t apply that code then the curor is not focused on teh log in.
Also (an issue with ie 7 I think) when you click REFRESH or BACK the user field does not clear (password field clears though).
My javascript knowledge is limited and I took the form from horizontal to vertical design, so maybe I’ve missed an element?
When you hit the back button on the browser you can have the label and the text box on top of each other, the only fix I see is to just have the label hide the text box
Anyone have a better idea?
Such as
I am somewhat disappointed that the techniques of the article “Prettier Accessible Forms”:http://www.alistapart.com/articles/prettyaccessibleforms weren’t used.
Wouldn’t a
Back in 2001 Aaron Boodman wrote Labels.js, an impressive first-take on this concept. Updating this idea, I wrote a script that uses the prototype.js library and unobtrusively crawls the page for input labels and places them inside the form elements. It might be of use to readers here:
“Stereolabels”:http://blog.stereodevelopment.com/code/stereolabels/
there is a bug with IE6 when this form is in a content with a position:relative. When rollover, input field stay fixed !
Too bad, can’t use it.
If somebody as an idea ?
You can also see : http://www.bossanoza.net/articles/formes_accessibles_et_compactes_avec_mootools
(I also posted this exact comment on the author’s personal blog where he mentioned the publishing of his article on this site. But I thought I would post here in case anyone would be interested in lending a hand to me)
Great tutorial. Newbie to web design here (CSS, JavaScript, etc.)
Background:
I wanted to make a search-box for the main page of my site that is sleek-looking with the label within the search field. When I did a simple google search, I saw something about using ‘onfocus’. This simple solution worked fine in Firefox, but when I tried that in IE6, a warning came on and I had to select “allow” to get the proper effect. I didn’t want to force my users to have to do that.
So I searched again. I saw in another forum that someone said to do a google search for “compact form” and that brought me to this article.
Using the techniques published, now IE6 fires up the form just fine without having the user select to “allow” the interactive functionality.
I was wondering about how to go about two things:
1) I would like the value that’s in the field to say “Please enter anything (name, city, zip, etc.) to get started” (I will make the field long enough to accomodate this). But I don’t think I want this sentence to be a label should JS be disabled.
Right? Or maybe it would be ok to let the label be this sentence, but wouldn’t it be too long with spaces and everything to be used correctly with the code?
Any advice on this?
Also, 2) What if I wanted two different submit boxes – one for “find” and one for “add” depending on what they wanted to do with what they entered. What’s the best way to go about this?
Any ideas would be much appreciated.
I’m encountering the problem that when the password field is automatically set based off of the user name value the label is not being removed.
Has anyone else encountered this?
It ends up with the starred password overlaying on the label that says “password”. I’ve tried to modify the script in various ways to correct for this, but have had no luck.
Can anyone help?
Accessible means “no loss of information for everyone”.
Here, when a text field has the focus or when it has a default value, how can the user know what he is supposed to enter? The label does not appear: information is missing. Not accessible. However, this is accessible for blind people, with a screen reader that doesn’t care about where is the label, visually speaking.
Please remember that accessibility is not only clean and well-formed XHTML code. And remember that blindness is not the only disability in the world.
Have to say this is a great idea.. Top Job! Only thing I would have said but has already been mentioned is the use of a fieldset and list to lay it out.
Westbrook, having the same issue with auto filled password field here. I haven’t found a reliable solution to fix this, unfortunately.