HTML and CSS Reference
In-Depth Information
Aligning Labels
Being a phrasing element and styled as inline by default, a label will be only as wide as its text content,
and that text will rest on the same baseline as its adjacent content, just as any ordinary text would. But
what if your form has a stack of several controls with labels of different widths? By default, it will look
something like Figure 8-35. Surely we can tidy this up a bit.
Figure 8-35 . Labels of different widths are staggered and unsightly
Inline phrasing elements can be treated as block-level with the simple CSS declaration display:block ,
overriding the browser's default style ( display:inline ). However, that will also cause the label s to each
appear on its own line—as any other block-level element would—rather than to the left of the control. If the
label element is instead floated to the left, the text field can then flow up onto the same line. It so
happens that any floated element is automatically styled as a block-level element as well, so the
display:block declaration isn't even necessary in combination with float:left .
Once the label s have become floating blocks, giving each of them the same width will push their related
text fields to the right, aligning them in a straight column. The text will still be aligned to the left of the label,
resulting in varying gaps of white space between the labels and their controls. You can align the text to the
right instead, and a margin will put some distance between the labels and their controls. Listing 8-31
shows the final CSS rule, converting all label elements within the element with the class ”info” (whatever
that element may be, even the parent form itself) to floating blocks 200 pixels wide.
Listing 8-31 . A CSS rule aligning the labels and controls into columns
.info label {
float: left;
width: 200px;
text-align: right;
margin-right: 15px;
You can see the results in Figure 8-36, where the labels and text fields now align in two neat columns. The
label text is aligned to the right, and the margin creates some space between the label and its control.
Figure 8-36 . The same form with the CSS applied
Search WWH ::

Custom Search