对齐标签和文本框

时间:2019-11-17 12:08:27

标签: html css

是否可以使用以下DOM内容或为标签或输入创建单独标签的幼稚方法为labelinput类型的空间分配50%的空间。

有问题的DOM。如何处理以下DOM

<label for="first">First Name: <input id="first" type="text"/></label>
<label for="last">Last Name: <input id="last" type="text"/></label>
<label for="email">Email: <input id="email" type="text"/></label>

视觉期望

标签宽度为50%

输入50%的宽度,并在其左侧对齐


幼稚的方法将标签和输入分开

<label for="first">First Name: </label><input id="first" type="text"/>
<label for="last">Last Name: </label><input id="last" type="text"/>
<label for="email">Email: </label><input id="email" type="text"/>

CSS

label {
    width: 50%;
}
input {
    width: 50%
}

4 个答案:

答案 0 :(得分:2)

如果您正在寻找一个过时的解决方案,则可以将输入浮动到右侧:

label {
  display: block;
  clear: both;
}

input {
  width: 50%;
  float: right;
}
<label>First Name: <input id="first" type="text"/></label>
<label>Last Name: <input id="last" type="text"/></label>
<label>Email: <input id="email" type="text"/></label>

您可以将每个标签设置为具有两列的网格样式:

label {
  display: grid;
  grid-template-columns: 50% 50%;
}
<label>First Name: <input id="first" type="text"/></label>
<label>Last Name: <input id="last" type="text"/></label>
<label>Email: <input id="email" type="text"/></label>

答案 1 :(得分:1)

两个版本:

label {
  display:flex;
  justify-content:space-between;
}
label > * {
  flex-basis:50%;
}
<label for="first">First Name: <input id="first" type="text"/></label>
<label for="last">Last Name: <input id="last" type="text"/></label>
<label for="email">Email: <input id="email" type="text"/></label>

label, input {
  display:inline-block;
  width:50%;
  box-sizing:border-box;
}
<label for="first">First Name: </label><input id="first" type="text"/>
<label for="last">Last Name: </label><input id="last" type="text"/>
<label for="email">Email: </label><input id="email" type="text"/>

答案 2 :(得分:1)

div {
  width: 600px;
  background: #ccc;
}

label {
  display: inline-block;
  width: 50%;
}
input {
  box-sizing: border-box;
  width: 50%
}
<div>
  <label for="first">First Name: </label><input id="first" type="text" />
  <label for="last">Last Name: </label><input id="last" type="text" />
  <label for="email">Email: </label><input id="email" type="text" />
</div>

display: inline-block;让您定义元素的尺寸,而无需像display: block;这样在元素后添加换行符。 box-sizing: border-box;让您将输入元素的边框包括在其宽度中(如果没有此宽度,则输入的实际宽度将超过50%,并会导致换行)。

如果您希望它们位于宽度为50%的单独行上,只需将inline-block更改为block,即可添加换行符。

答案 3 :(得分:0)

试试这个。 将标签和输入内容嵌套在桌子边,并为

使用50%或50vw的宽度
相关问题