对齐<input />和<option>标签的方式相同

时间:2019-02-27 16:54:21

标签: html css html-form

我正在尝试制作一个<form>和所有<input><select>选项对齐的方法,例如:desired result

但是,这是我的结果:my result

如您所见,文本<input>正确对齐,但是下拉菜单与它们不对齐。我的代码在下面。

HTML

<form id="survey-form">
    <div class="row">
      <label for="name">* Name:</label>
      <input type="text" id="name" class="input-field" required placeholder="Enter your name">
    </div>
    <br>
    <div class="row">
      <label for="email">* Email:</label>
      <input type="email" id="email" class="input-field" required placeholder="Enter your email">
    </div>
    <br>
    <div class="row">
      <label for="number">*Age:</label>
      <input type="number" min="1" id="number" required class="input-field" placeholder="Age">
    </div>
    <br>
    <div class="row">
      <label for="role">Which option best describes your current role?</label>
      <select name="role" id="role" class="input-select">
    <option value="student">Student</option>
    <option value="full-time-job">Full Time Job</option>
    </div>
    <option value="full-time-learner">Full Time Learner</option>
    <option value="prefer-not-to-say">Prefer not to say</option>
    <option value="other">Other</option>
    </select>
  </form>

CSS

.row {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.input-field {
  margin-left: 1em;
  padding: .5em;
  margin-bottom: .5em;
  height: 20px;
  width: 280px;
  border: 1px solid gray;
  border-radius: 2px;
}
.input-select {
  margin-left: 1em;
  padding: .5em;
  margin-bottom: .5em;
  width: 100px;
  height: 40px;
  border: 1px solid gray;
  border-radius: 2px;
}

我尝试调整justify-contentalign-itemsdisplay和其他相关CSS,但似乎没有使我的<select><input>适应排在一起。

1 个答案:

答案 0 :(得分:1)

  

Codepen demo

从代码开始,一种简短的方法可能是:

1-在表单中添加一个左/右页边距,并同时分配一个width和一个max-width,例如

#survey-form {
  width: 70%;
  max-width: 640px;
  margin: 0 auto;
}

2-在flex-basislabel / input字段上给与相等的select。还要分配box-sizing: border-box

.row > * {
  flex-basis: 50%;
  box-sizing: border-box;
}

3-将标签向右对齐

.row label {
  text-align: right;
}