如何使用CSS网格在列之间分配水平空间

cbjzeqam  于 9个月前  发布在  其他
关注(0)|答案(2)|浏览(69)

我需要为一些数据创建一个类似表格的结构。一半的行需要被分成列(图片中为灰色),另一半需要只有一列,并且应该跨越整个宽度。此外,宽行之后需要有一个边距,这是我不能使用<table>的主要原因。


的数据
在下面的代码片段中,我使用网格和grid-template-columns: repeat(3, 1fr);实现了我的目标。然而,它只在我有3个灰色列的情况下有效。实际上,我事先不知道宽行上方有多少列。我正在寻找一种解决方案,它适用于动态数量的灰色列(由标记中div s的数量决定)。
我尝试在列模板中使用auto-fill,但是它没有扩展灰色列来填充行的宽度。列受到给定的100px值的限制。
如何让灰色列填充整个行,而无需在CSS中指定列数?

.container {
  width: 100%;
  margin-bottom: 10px;
}

.row {
  display: grid;
  margin-bottom: 5px;
}

.row.static-repeat {  
  grid-template-columns: repeat(3, 1fr); 
}

.row.auto-fill {  
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); 
}

.cell {
  border: 1px solid black;
  background-color: lightgray;
}

.wide {
  grid-column: 1 / -1;
  background-color: wheat;
}

个字符

1mrurvl1

1mrurvl11#

这是一个flexbox作业

.container {
  margin-bottom: 10px;
}

.row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 5px;
}

.cell {
  flex: 1;
  min-width: 0;
  background-color: lightgray;
  border: 1px solid black;
}

.wide {
  flex: 100%;
  background-color: wheat;
}

个字符

sg2wtvxw

sg2wtvxw2#

如果grid的使用不是强制性的,那么使用flex很容易实现:

p {
 display: flex;
 flex-wrap: wrap;
 margin: 1ch;
 background-color: black; /* For "collapsed borders"… */
 gap: 1px; /* …between "cells"… */
 padding: 1px; /* …and around. */
 color: white;
}
p > * {
 flex-grow: 1; /* Fill unclaimed space. */
 flex-basis: 0; /* Disregard width of the content. */
 padding: 0 1ch;
 background-color: lightgrey;
 color: black;
}
p > *:last-child {
 flex-basis: 100%; /* Full width. */
 background-color: wheat;
 color: black;
}

个字符

相关问题