Center an input field with css

css, html

Solution

Sticking to your method, here's a working fiddle: http://jsfiddle.net/bmkc2/1/

- to be taken into consideration, a width can't be applied on an inline element like a `span`. You first have to display it as inline-block for example.

- `display: block` on input will display it alone on its own line. Again, inline-block or floating.

- inline-block has one annoyance (it's normal but still annoying here), it'll display whitespace between elements displayed as inline-block, that is a 4px space between each span and input. The HTML comments are there to avoid these spaces (it's normal because imagine two words each in a span and separated by a space. You need and expect this space between words or it'd be unreadable!)

- width: 20% and border-width: 1px and padding 5px will add up and with 2x40% it'll be greater than 100%. `box-sizing: border-box` will avoid that border and padding are taken from the 20% width (check caniuse.com for the complete list of prefix to add -moz-, etc).

edit:

- your input has neither a label (associated with its `for` attribute) nor a title attribute, is it just because it's a demo ?

- `margin: 0 auto` as stated in another answer and `text-align: center` are preferable to adding 2 empty elements just for centering. I just wanted to make your first try work.

Problem

I have an input field an width of 20% like you can see here: ``` <input id="saveServer" width="20%" class="depth"></input> ``` So to center it i add two span elements,with an width:40%, before and after the input field, to center the input field. Like you can see here: ``` <span style="width:40%"></span> <input id="saveServer" width="20%" class="depth"></input> <span style="width:40%"></span> ``` But somehow the the inut field does not center himself. I have no idea how to center it! Greetings from Germany! Thanks! Heres the same example on fiddle:http://jsfiddle.net/bmkc2/

Original source