2012-02-26 270 views
1

我正在尝试为所有浏览器访问。不同的浏览器给出了不同的结果(IE对我来说最成问题)。我包含了截图,以便您可以看到我在说什么。HTML表单对齐 - 输入与标签

这是形式的外观在Safari,Firefox和Chrome:

enter image description here

http://imageshack.us/photo/my-images/210/bildschirmfoto20120226u.png/

这是形式的外观在IE6和IE7:

enter image description here

http://imageshack.us/photo/my-images/37/bildschirmfoto20120226u.png/

这是IE8和IE9:

enter image description here

http://imageshack.us/photo/my-images/39/bildschirmfoto20120226u.png/

HTML

<form method="post" action="?test" id="form"> 
    <label for="user">USERNAME</label> 
    <input type="text" name="user" id="user" maxlength="100" title="Please enter your username." data-h5-errorid="empty-user" tabindex="1" required /> 
    <div id="empty-user" class="fail">This stuff will get replaced by the title contents.</div> 
    <label for="password" class="clear">PASSWORD</label> 
    <input type="password" name="password" id="password" maxlength="100" title="Please enter your password." data-h5-errorid="empty-password" tabindex="2" required /> 
    <div id="empty-password" class="fail">This stuff will get replaced by the title contents.</div> 
</form> 

CSS

label { 
    background: yellow; 
    font-size: 12px; 
    font-weight: bold; 
    width: 100px; 
    float: left; 
    margin-right: 50px; 
    text-align: right; 
    cursor: pointer; 
} 

input { 
    height: 30px; 
    background-color: #fafafa; 
    border: 1px solid #abaaaa; 
    width: 300px; 
    margin: 5px 0 5px 0; 
    float: right; 
} 

现在我的问题是,我如何对齐标签,使它们与输入字段垂直对齐?我在这里使用了搜索,大部分时间都是这样的:

vertical-align: middle; 

被推荐,但这根本不起作用。 Safari,Chrome和Firefox的唯一修正是为标签添加边距顶部或顶部填充,但这会破坏IE8和IE9中的表单。

我该怎么处理这个问题?降低输入字段的高度对我来说不是一种选择。

+0

我会*真*推荐**不**使用'元素'这样的选择器;使用像'form label.text'这样的类选择器,或者像'#form label'这样的后代选择器。只是它不适用于页面上每种*类型的元素。 – 2012-02-26 00:23:49

+0

好的,谢谢,我会的! – Sven 2012-02-26 00:28:55

回答

4

在输入标签(某处)后放置一个clear:both

我建议你在你的表单中增加更多的标记用于额外的定制。通常我喜欢做这样的表格:

<div class="field"> 
    <label for="user">USERNAME</label> 
    <div class="field-subject"> 
     <input type="text" name="user" id="user" maxlength="100" title="Please enter your username." data-h5-errorid="empty-user" tabindex="1" required /> 
    </div> 
</div> 

.field { 
    overflow: auto; /* this "clears" the floated elements */ 
    margin-bottom: 10px; 
} 

.field label { 
    float: left; 
    width: 200px; 
} 

.field .field-subject { 
    float: left; 
    width: 500px; 
} 
+0

这将'垂直对齐'标签中的文字? – 2012-02-26 00:29:51

+0

我相信你可以尝试...如果这不起作用,你可以将标签设置为'display:block'并添加一些边距/填充。 – Matthew 2012-02-26 00:34:18