When creating a web form you have to make a functional and visually aligned layout. The simplest way to do this is to place elements in a table or by fixing width of labels. Tables stretch its cells according to width of largest element in a column. That way you can have aligned form. Fixing label width will also also allow you to have a hard-coded but aligned form.
But what if you don't want to use tables? Or what if you don't know how long labels could be because you are developing an application that has many localized strings? And you still want to align input elements according to the width of the longest label?
Then you can justify all labels. By justifying I mean to make them same width. And the simplest way to do this is to use jQuery.
If you create a simple web form like in the example below all you have to do is to set float:left and display:block for both label and input field.
These are the CSS styles:
Looks familiar? Usually, you would set the width of labels to some number, let's say 100px. But, let's do another thing. Let's calculate the width of a largest label and apply it to all labels. jQuery function below does exactly what I wrote:
var max = 0;
if ($(this).width() > max)
max = $(this).width();
And visually it looks like this:
It's easy to do many tricks using jQuery and this was just one of them. Maybe there are simplest solutions to do this, but it was fun to see putting jQuery in most common scenarios like this one.
Thanks for reading. Let's discuss this on twitter.