HTML CSS 表单 - 如何使表单在​​页面上居中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15665607/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 06:56:02  来源:igfitidea点击:

HTML CSS Form - How to center the form on the page?

htmlcssformsmargin

提问by Sourabh

I made a form and I am trying to center it on page but it doesn't work. I tried applying these 2 CSS to it but it didn't work.

我做了一个表格,我试图将它放在页面上,但它不起作用。我尝试将这 2 个 CSS 应用于它,但没有用。

form{margin: 0 auto;}

form{margin: auto;}

I also tried enclosing the form into div.container and applying same CSS to it but still nothing.

我还尝试将表单包含在 div.container 中并对其应用相同的 CSS,但仍然没有。

But this works:

但这有效:

{margin: 0 250px 0;}

Form here

形成这里

回答by mattytommo

You need to do two things to achieve this:

你需要做两件事来实现这一点:

1) Change inline-blockdisplay on the form to be block.
2) Fix the width (you currently have it as auto).

1)inline-block将表单上的显示更改为block
2) 修复宽度(您目前将其设为auto)。

Demo: http://jsfiddle.net/bMf9M/2/

演示:http: //jsfiddle.net/bMf9M/2/


Or if you don't want to fix the form size, you can use text-align: center(Thanks @donderpiet)


或者,如果您不想修复表单大小,则可以使用text-align: center(感谢@donderpiet)

Demo: http://jsfiddle.net/bMf9M/4/

演示:http: //jsfiddle.net/bMf9M/4/

回答by Piet van Dongen

Your formhas a property display: inline-block;, which makes it behave like an inline element. So you have to add text-align: center;to its parent to make it center horizontally. Like this: http://jsfiddle.net/bMf9M/4/.

form有一个属性display: inline-block;,这使它的行为像一个内联元素。所以你必须添加text-align: center;到它的父级以使其水平居中。像这样:http: //jsfiddle.net/bMf9M/4/

Don't forget to set the form's text-alignto left, otherwise it will have center-aligned text.

不要忘记将表单的设置text-alignleft,否则它将具有居中对齐的文本。

回答by thatidiotguy

You have to specify the width of the container as elements with display:blockproperty automatically size to the maximum width of their container.

您必须将容器的宽度指定为具有display:block自动大小为其容器最大宽度的属性的元素。

回答by Christian Ziemer

You need to set a Width if you like to use margin:auto;

如果您喜欢使用 margin:auto,则需要设置 Width;