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

2019-03-05 08:06发布

问题:

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.

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.

But this works:

{margin: 0 250px 0;}

Form here

回答1:

You need to do two things to achieve this:

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

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


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

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



回答2:

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



回答3:

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



回答4:

Your form has 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/.

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