Floating Form Labels
I seem to always forget this, so hopefully blogging about it will help me remember and serve as a future reference.
We're using labels to line up form elements like so:
No problem. Everything looks great. Now I'll take that same concept but add some disparity in the heights of the label and the content. For this example, let's use a <div> with multiline content. Let's put borders around the content areas so that we can see what's going on.
Here is the HTML:
Some CSS like this might work:
-
label {border: 1px dashed maroon; width: 95px; float: left; text-align: right; font-weight: Bold;}
-
div.row {margin-bottom: 7px;}
-
div.row div {border: 1px dashed green; }
That should produce something like this:
What a very nice message indeed.
I love messages.
Oh my. That's not the effect I was shooting for. But look at the green borders of the inner divs. They aren't next to the floated label like I'd expect; they are on top of it, but their content still flows around the floated label, which is why the first example above with the text fields looks fine, but this multiline div reveals the actual behavior the div has when it sits below a floating element.
Right around now is when I'm cursing floats and dreaming of the days of table-based layouts.
This behavior is actually intentional though, and once you understand it, it isn't hard to work with. Like the Float Basics page on Floatutorial points out:
A floated box is laid out according to the normal flow, then taken out of the flow and shifted to the left or right as far as possible. Content can flow down the right side of a left-floated box and down the left side of a right-floated box.
That explanation makes the behavior make perfect sense. The label is taken out of the flow, and thus the <div> sits on top of it. Once you understand that, it is easy to see that a left margin or padding will take care of the div's alignment.
This change:
-
div.row div {margin-left: 105px; border: 1px dashed green;}
Produces the desired effect:
What a very nice message indeed.
I love messages.
The final result, without the borders:
What a very nice message indeed.
I love messages.
