2012-11-02 71 views
17

我是新来的CSS,并有一个简单的登录表单,我试图正确对齐。基本上是两列,一列是标签和登录按钮,另一列是文本框。我如何在CSS中做到这一点?在CSS中对齐表单元素

的HTML代码是

<body> 
    <form action="" method="post"> 
    <label> Username </label> 
    <input type="text"/> 

    <label> Password </label> 
    <input type="password"/> 

    <input type="submit" value="submit"/> 
    </form> 
</body> 
+1

输入密码和用户名后只需加上
。 – Vucko

回答

25

这是一个办法,工作原理:

form { 
    width: 80%; 
    margin: 0 auto; 
} 

label, input { 
    /* in order to define widths */ 
    display: inline-block; 
} 

label { 
    width: 30%; 
    /* positions the label text beside the input */ 
    text-align: right; 
} 

label + input { 
    width: 30%; 
    /* large margin-right to force the next element to the new-line 
     and margin-left to create a gutter between the label and input */ 
    margin: 0 30% 0 4%; 
} 

/* only the submit button is matched by this selector, 
    but to be sure you could use an id or class for that button */ 
input + input { 
    float: right; 
} 
​ 

JS Fiddle demo

调整尺寸和边距以适合您的用例和美学。

+0

@Jacob:谢谢!这可能是一个非常令人困惑的预编辑语句! XD –

+0

又一个男人 - 好名字@DaveThomas –

3

对于你所要求的,我只是简单地把它们放在一张桌子上。

<form action="" method="post"> 
    <table> 
     <tr> 
      <td><label> Username </label></td> 
      <td><input type="text"/></td> 
     </tr> 
     <tr> 
      <td><label> Password </label></td> 
      <td> <input type="password"/></td> 
     </tr> 
     <tr> 
      <td colspan="2"><input type="submit" value="submit"/></td> 
     </tr> 
    </table> 
    </form>  

下面是它的样子 http://jsfiddle.net/wCSAn/

+10

这不是表格数据,所以不应该在表格中 – Neil

+2

问题如何在CSS中完成。虽然桌子很诱人,因为他们完成了工作,但这不是好习惯。 –

+1

有行和列 - 这是一张桌子。 – dcromley

2

我回答在我的博客文章这样一个问题:https://wscherphof.wordpress.com/2015/06/17/right-align-form-elements-with-css/

它指的是这个小提琴:https://jsfiddle.net/wscherphof/9sfcw4ht/9/

剧透:float: right;是正确的方向,但它需要更多的关注才能获得整洁的结果。

+0

+1提供4种不同的方法,很好地整理和解释。但是,如果这些链接死亡,这个答案将是无用的。请花时间直接在答案中简要描述您的解决方案。 –