使用 CSS 将所有 HTML 表单元素居中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1803237/
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
Centering all HTML form elements using CSS
提问by yos
How do you center all form label and input fields using CSS?
如何使用 CSS 将所有表单标签和输入字段居中?
How would you do this for a form with label text (block) on top of the input field?
对于在输入字段顶部带有标签文本(块)的表单,您将如何执行此操作?
#fieldset label {
display: block;
}
#fieldset input {
font-size: 0.8em;
height: 1.2em;
width: 15em;
}
回答by darasd
As Boldewyn and Ben said, text-align will centre inline items (such as spans). To centre block elements (such as divs and forms and paragraphs), give it a width and set margin-right and margin-left to auto.
正如 Boldewyn 和 Ben 所说, text-align 将使内联项目(例如跨度)居中。要居中块元素(例如 div、表单和段落),请为其指定宽度并将 margin-right 和 margin-left 设置为 auto。
It's important to understand the difference between block and inline elements.
了解块元素和内联元素之间的区别很重要。
回答by Boldewyn
form {
text-align: center;
}
It depends on both your HTML and your current CSS. The above is a starting point.
这取决于您的 HTML 和您当前的 CSS。以上是一个起点。
回答by orip
The usual "centering" used for form labels and inputs is actually 2 columns, labels right-aligned and input-fields left-aligned.
通常用于表单标签和输入的“居中”实际上是 2 列,标签右对齐,输入字段左对齐。
One way to do this without tables is to give the label elements the same width and right-align them, for example:
在没有表格的情况下执行此操作的一种方法是为标签元素提供相同的宽度并将它们右对齐,例如:
<style type="text/css">
.foolabel{width:10em;text-align:right;display:inline-block;margin-right:1em;}
.formlist{list-style:none}
</style>
<ul class="formlist">
<li><label class="foolabel">Name:</label><input type="text" /></li>
<li><label class="foolabel">Quest:</label><input type="text" /></li>
<li><label class="foolabel">Favorite Color:</label><input type="text" /></li>
</ul>