小编典典

在CSS中对齐表单元素

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>

阅读 839

收藏
2020-05-16

共1个答案

小编典典

这是一种有效的方法:

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

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

2020-05-16