The trouble with the right-alignment of input fields

Posted by Jason on July 11, 2008 at 11:32 am

Everyone knows that when you have a text box which accepts a number, it should automatically right-align the text content. Well maybe not everyone, but accountants certainly do and if you’re writing an application for an accountant it just won’t look right unless the values are right-aligned.

Simple, I thought - text-align:right in the CSS and the jobs a good ‘un. Well yes, you would think so. The fact of the matter is that text-align:right is only supposed to apply to block level elements (according to the CSS2 specs), although it isn’t quite implemented that way in all browsers. So, add display:block in there as well just to be on the safe side:

Left Align: <input style=”padding: 0px; text-align: right; display: block” type=”text” />

Right Align: <input style=”padding: 0px; display: block” type=”text” />

Job done! Well, not quite if you are viewing this in Internet Explorer 7. Click in the input field which is aligned to the right and no cursor displays at all! I must be tired today because this took me ages to work out and I found no reference to it anywhere in the web. For some reason the cursor is there - it’s just off to the right a little too far. I say ’some reason’ when I now know that the actual reason is that the padding is set to 0px. The reason for this happens to be because it has inherited the property from other elements in my form layout, but in this example I have added it specifically. Add a little padding to the right and hey presto:

Left Align: <input style=”padding: 0px 1px 0px 0px; text-align: right; display: block” type=”text” />

Right Align: <input style=”padding: 0px 1px 0px 0px; display: block” type=”text” />

That’s just strange. Zero padding displays the cursor on the left, but not the right. Except in Firefox, which just shows it correctly in either case.