【发布时间】:2021-05-19 07:18:51
【问题描述】:
我想在更宽的屏幕上以两列显示带有标签和表单元素的表单,并在较小的屏幕上显示带有交替标签/输入的单列。
所以我需要离开
label
input
label
input
在小屏幕上
label | label
input | input
在较大的。我想使用 flexbox,因为我需要支持 IE11,而且我认为尽管它有怪癖,但支持它比实现新旧网格语法更容易。
我可以使用:nth-of-type()(见下文)来实现这一点,如果没有任何其他解决方案,我会这样做,但我需要知道表单中将出现的元素数量和以后表单元素的数量发生变化时,我必须扩展 CSS。
我还可以将每个标签/表单元素对包装在一个容器中并将它们并排放置,但我还想考虑具有不同高度的标签和输入(参见带有标签 3 + 4 的行),其中行不通(它需要像 subgrid 这样的东西来实现这一点)。
.container {
display: flex;
flex-wrap: wrap;
}
.container>* {
width: 50%;
box-sizing: border-box;
}
.container label {
margin-top: 0.3em;
align-self: flex-end;
}
.container input {
margin-top: 0.3em;
align-self: flex-start;
}
@media screen and (min-width: 400px) {
.container label:nth-of-type(1),
.container label:nth-of-type(2) {
order: 1;
}
.container input:nth-of-type(1),
.container input:nth-of-type(2) {
order: 2;
}
.container label:nth-of-type(3),
.container label:nth-of-type(4) {
order: 3;
}
.container input:nth-of-type(3),
.container input:nth-of-type(4) {
order: 4;
}
.container label:nth-of-type(5),
.container label:nth-of-type(6) {
order: 5;
}
.container input:nth-of-type(5),
.container input:nth-of-type(6) {
order: 6;
}
}
<div class="container">
<label>label1</label>
<input placeholder="input1">
<label>label2</label>
<input placeholder="input2">
<label>label3</label>
<input placeholder="input3">
<label>label4<br>lorem ipsum</label>
<input placeholder="input4">
<label>label5</label>
<input placeholder="input5" style="height: 3em">
<label>label6</label>
<input placeholder="input6">
</div>
有没有更优雅/更动态的方式来做到这一点?
【问题讨论】: