Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center an input field with css

Tags:

html

css

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/

like image 567
Em Sta Avatar asked Dec 01 '25 11:12

Em Sta


2 Answers

I think more context would help to clarify the problem, but is this what you are after? One way to center the input itself is by adding the rule:
margin: 0 auto;

http://jsfiddle.net/QqRCm/

like image 183
mg1075 Avatar answered Dec 03 '25 02:12

mg1075


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.
like image 30
FelipeAls Avatar answered Dec 03 '25 02:12

FelipeAls



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!