在 CSS 中对齐表单元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13204002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Align form elements in CSS
提问by DavidL
I'm new to CSS and have a simple login form that I'm trying to align correctly. Basically two columns with the labels and the Loginbutton in one column and the text boxes in another column. How do I do this in CSS?
我是 CSS 新手,有一个简单的登录表单,我正在尝试正确对齐。基本上是两列,其中一列带有标签和登录按钮,另一列带有文本框。我如何在 CSS 中做到这一点?
The HTML code is:
HTML代码是:
<body>
<form action="" method="post">
<label> Username </label>
<input type="text"/>
<label> Password </label>
<input type="password"/>
<input type="submit" value="submit"/>
</form>
</body>
回答by David says reinstate Monica
This is one approach that works:
这是一种有效的方法:
form {
width: 80%;
margin: 0 auto;
}
label, input {
/* In order to define widths */
display: inline-block;
}
label {
width: 30%;
/* Positions the label text beside the input */
text-align: right;
}
label + input {
width: 30%;
/* Large margin-right to force the next element to the new-line
and margin-left to create a gutter between the label and input */
margin: 0 30% 0 4%;
}
/* Only the submit button is matched by this selector,
but to be sure you could use an id or class for that button */
input + input {
float: right;
}
?
Adjust dimensions and margins to suit your use-case and aesthetic of course.
当然,调整尺寸和边距以适合您的用例和审美。
回答by TheLawrence
For what you are asking, I'd simply put them in a table.
对于你所问的,我只是把它们放在一张桌子上。
<form action="" method="post">
<table>
<tr>
<td><label> Username </label></td>
<td><input type="text"/></td>
</tr>
<tr>
<td><label> Password </label></td>
<td> <input type="password"/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="submit"/></td>
</tr>
</table>
</form>
Here's what it will look like http://jsfiddle.net/wCSAn/
这是它的样子 http://jsfiddle.net/wCSAn/
回答by vaibnak
You can also use the position property in CSS to align your labeland inputin certain specified way as you want. By this, they get arranged in accordance to the parent element.
您还可以根据需要使用 CSS 中的 position 属性以某种指定的方式对齐标签和输入。通过这种方式,它们按照父元素进行排列。
form {
position: relative;
width: 70%;
text-align: right;
}
label {
width: 30%;
position: absolute;
left: 10%;
text-align: right;
margin-right: 30px;
}
input[type=submit] {
position: absolute;
left: 25%;
background-color: #9AE5F8;
}
Here is the link to its jsfiddle.
这是其jsfiddle的链接。