开发者

Centering all HTML form elements using CSS

开发者 https://www.devze.com 2022-12-12 09:10 出处:网络
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?

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;
}


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.


form {
  text-align: center;
}

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


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号