CSS:右侧标签,浮动左侧包裹缩放

时间:2017-04-16 20:05:52

标签: html css forms word-wrap

我有一个包含legendfieldset s的表单,需要在label s的左侧显示input

我想仅使用CSS来设置我的form label,但CSS选择器无法找到前一个兄弟,所以我需要在HTML代码中label之后编写input为了选择与无效label相关联的input,并使用float: left

如果填写input错误,则需要更改相应的标签。 在以下示例中,标签变为红色,验证失败描述消息展开。

描述label需要与相应的输入位于同一行(出于审美目的),或者至少左上角应该与input的最右边点对齐。

当我尝试放大时会出现问题。 我通过将较低宽度设置为外部div来模拟这一点。



#container {
  width: 200px;
}

form {
  border: 1px solid red;
  overflow: auto;
}

fieldset {}

section {}

input[type="text"] {
  display: inline-block;
}

input[type="text"]+label {
  display: inline-block;
  float: left;
  text-align: right;
  width: 80px;
}

input[type="text"]:invalid+label {
  color: red;
}

input[type="text"]+label+label {
  display: none;
}

input[type="text"]:invalid+label+label {
  display: inline-block;
  color: red;
}

.field-row {
  display: inline-block;
  white-space: nowrap;
}

<div id="container">
  <form>
    <fieldset>
      <legend>Fieldset</legend>
      <section>
        <div>
          <div class="field-row">
            <input id="first" type="text" value="" required />
            <label for="first">First</label>
            <label>
             Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
            </label>
          </div>
        </div>
        <div>
          <div class="field-row">
            <input id="second" type="text" value="" />
            <label for="second">Second</label>
          </div>
        </div>
      </section>
    </fieldset>
  </form>
&#13;
&#13;
&#13;

在此代码段中,您可以看到第一行非常宽,超出外部fieldset(至少在Google Chrome中)。 如果我对overflow: auto使用fieldset,则移动滚动条时会向左移动legend文字。

如果需要input有效,则相应的label会转到另一行,但我需要将label放在连接input的一行上。

帮助我的黑客,是将min-width块的field-row设置为宽于label + input宽度。 但是,这需要知道它们的最大允许宽度,并使用JavaScript或在依赖字段的任何paddingmarginwidth更改中更改它。

当我不使用float时,它也很有效。 虽然,此方法需要使用JavaScript来更改label更改中的更改input

我制作了ReactJS个应用,因此JavaScript不是问题, 但我想尽可能多地调查和使用CSS功能。

1 个答案:

答案 0 :(得分:1)

如果您只需要支持现代浏览器,我建议您放弃尝试使用float,而是使用flexbox。

您需要做的就是创建let div .field-row,然后为输入和标签元素设置display: flex;属性。像这样:

&#13;
&#13;
order
&#13;
#container {
  width: 200px;
}

form {
  border: 1px solid red;
  overflow: auto;
}

fieldset {}

section {}

input[type="text"] {
  order: 2;
}

input[type="text"]+label {
  text-align: right;
  order: 1;
  width: 80px;
}

input[type="text"]:invalid+label {
  color: red;
}

input[type="text"]+label+label {
  display: none;
  order: 3;
}

input[type="text"]:invalid+label+label {
  color: red;
  display: inline;
}

.field-row {
  display: flex;
  white-space: nowrap;
}
&#13;
&#13;
&#13;

相关问题