CSS网格布局:用更少的输入指定网格位置?

时间:2019-10-27 21:11:41

标签: html css layout css-grid

(我正在尝试使用CSS Grid布局将此数据输入页面从非常原始的CSS / HTML“表”布局转换为更好的布局)。

看来,按照惯例,我已将其宽12列。每个输入字段都有一个宽度相同的标签。换句话说,我的CSS目前非常重复:

.container {
  display: grid;
  grid-template-columns: repeat(12, minmax(0, 1fr));
  grid-gap: 10px;
}

#SigNameLabel {
  grid-column: 1 / 13;
  grid-row: 2;
}

#SignatureName {
  grid-column: 5 / 13;
  grid-row: 2;
}

#PaymentNoLabel {
  grid-column: 1 / 13;
  grid-row: 3;
}

#PaymentNo {
  grid-column: 5 / 13;
  grid-row: 3;
}

#CurrencyLabel {
  grid-column: 1 / 13;
  grid-row: 4;
}

#Currency {
  grid-column: 5 / 13;
  grid-row: 4;
}

* {
  border: 1px solid #999;
}        
<div class="container">
  <div id='SigNameLabel' class='unselectable'>Signature name:</div>
  <div id='SignatureName' class='unselectable dataField single-line'></div>

  <div id='PaymentNoLabel' class='unselectable'>Payment No:</div>
  <div id='PaymentNo' class='unselectable dataField single-line'></div>

  <div id='CurrencyLabel' class='unselectable'>Currency:</div>
  <div id='Currency' class='dataField single-line'></div>
</div>

使用JS以自动化方式“创建”布局的捷径,即通过分析DIVs中的container,有什么方法可以使CSS不再那么繁琐和显式,而仅仅是“从“ HTML的作用”开始?

例如,我不得不在这里为每个标签提供一个特定的ID:当它们各自坐在自己的TD中时,它们并不需要它。是否可以给每个这样的标签DIV一个类,例如left-hand-column,以某种方式可以将它们全部应用grid-column: 1 / 13,以某种方式将grid-row应用于它们,他们右边的数据字段DIV

1 个答案:

答案 0 :(得分:1)

您可以像下面那样简化代码。而且您不一定需要12列

.container {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  grid-gap: 10px;
}

.container>*:nth-child(even) {
  grid-column: span 2;
  border:1px solid;
}
.container>*:nth-child(odd) {
  /* Not sure if you need this but it will allow 
     the full width of the grid like your code grid-column: 1 / 13;
  width:calc(300% + 2*10px); */
  border:1px solid red;
}
<div class="container">
  <div id='SigNameLabel' class='unselectable'>Signature name:</div>
  <div id='SignatureName' class='unselectable dataField single-line'></div>

  <div id='PaymentNoLabel' class='unselectable'>Payment No:</div>
  <div id='PaymentNo' class='unselectable dataField single-line'></div>

  <div id='CurrencyLabel' class='unselectable'>Currency:</div>
  <div id='Currency' class='dataField single-line'></div>
</div>