5

How do you center all form label and input fields using 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;
}
gevorg
  • 4,835
  • 4
  • 35
  • 52
yos
  • 223
  • 2
  • 3
  • 7
  • what exactly do you mean? do you want to centre the form within the page? or the elements within the form? or the text within the elements? – darasd Nov 26 '09 at 11:55
  • i'd like to center both! – yos Nov 26 '09 at 12:05
  • A Frequently Duplicated Question. The most recent dupe I'm aware of is , which also has a useful answer or two. – Carl Smotricz Nov 26 '09 at 12:16
  • Lemme try that link again: http://stackoverflow.com/questions/1798817/why-is-the-center-tag-deprecated-in-html – Carl Smotricz Nov 26 '09 at 12:17
  • i've actually thoroughly googled for an answer to my specific case... couldn't find one. in a way, it's basically just a css replacement for center, but you don't think of that when you encounter the problem from the other side. – yos Nov 26 '09 at 12:20
  • @carl-smotricz ... just tried the margin: 0 auto solution in the link you sent. does not solve my problem. :-( – yos Nov 26 '09 at 12:24

3 Answers3

8

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.

It's important to understand the difference between block and inline elements.

Daniel Dušek
  • 13,683
  • 5
  • 36
  • 51
darasd
  • 2,899
  • 3
  • 26
  • 39
5
form {
  text-align: center;
}

It depends on both your HTML and your current CSS. The above is a starting point.

Boldewyn
  • 81,211
  • 44
  • 156
  • 212
1

The usual "centering" used for form labels and inputs is actually 2 columns, labels right-aligned and input-fields left-aligned.

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>
orip
  • 73,323
  • 21
  • 116
  • 148