简体   繁体   中英

Aligning text vertically inside a label div

Example of problem http://img638.imageshack.us/img638/3733/97914817.jpg

I'm trying to recode one of my older forms. It was filled with tables that I want to replace with CSS. However I'm having trouble having text and a form element aligned vertically together. As the picture shows the text defaults to starting at the top instead of in the middle. The blue highlights around the row is dreamweavers interpretation / selection of what is going on.

I have label and input divs, both floated left, inside a div called #light, which is inside a general container. This is what my css code looks like:

#contentBox{
 width: 600px;
 float: left;
 background-color: #e2e2e2;
 overflow: auto;
 border-color: #c5c5c5;
 border-width: 1px;
 border-style: solid;
 font-size: 12px;
}
#light {
 float: left;
 width: 500px;
 padding: 15px;
 background-color: #e2e2e2;
 margin: 7px;
 border-color: #c5c5c5;
 border-width: 1px;
 border-style: solid;
 vertical-align: middle;
}
input {
 float: right;
 width: 20em;

}
label {
 float: left;
 text-align: right;
 vertical-align: baseline;
}

Any idea what the problem is? I've tried swapping around the vertical-align in different divs, floating in different directions, getting rid of the label but I just end up with more problems rather than less.

You cannot use vertical-align on elements unless they are table cells (or displayed as such) as this article explains. Set line-height to the element height if you've only got one row of text.

Usually, to solve that problem, I use the line-height property:

Ex:

div{width:600px;font:normal normal 12px/30px Arial, Helvetica, sans-serif;}

This will set the font to 12px, and the line-height to 30px, keeping the font vertically align within the 30px of its line.

Vertical alignment of text can be incredibly annoying or incredibly easy.

If the size of all the involved elements are known, your best bet is to set manual padding/margins on the text itself to make sure it's aligned.

If the content you want to center vertically is dynamic, this is your best bet .

Not sure, but your input tag is set to "float:right", so its height won't be taken into account by the parent. Hence, the height of the parent is actually probably the height of the label (I suspect dreamweaver is not interpreting correctly what browsers do.) Try to remove the float on the input tag and see if it makes a difference.

Vertical alignment can be applied only to inline elements. The best solution is to modify your HTML and make it like in this examples

您可以寻求“便宜”的解决方案,并将padding-top应用于标签div。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM