Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

Align form elements in CSS

I'm new to CSS and have a simple login form that I'm trying to align correctly. Basically two columns with the labels and the Login button in one column and the text boxes in another column. How do I do this in CSS?

The HTML code is:

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

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

    <input type="submit" value="submit"/>
  </form>
</body>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is one approach that works:

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;
}
<form action="#" method="post">
  <!-- note that I've added a 'for' attribute to
       both of the <label> elements, which is
       equal to the 'id' attribute of the relevant
       <input> element; this means that clicking
       the <label> will focus the <input>: -->
  <label for="username">Username</label>
  <input id="username" type="text" />

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

  <input type="submit" value="submit" />
</form>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...