【问题标题】:Use a table or flexbox to create a grid-like UI使用表格或弹性框创建类似网格的 UI
【发布时间】:2018-01-07 05:20:20
【问题描述】:

我需要创建一个带有行和列的类似网格的 UI。 主要要求是列和行适应单元格内容。 例如,第 1 列具有放置在第 1 列、第 1 列单元格中的文本的宽度。 第1行的高度是第1行,第2列的单元格的高度。

单元格内容是文本和单选按钮。

我可以用 flex-box 还是只用好的旧桌子来做这件事? 有什么例子吗?

使用 flexbox 我想我需要嵌套的 flexbox 吗?不确定。

【问题讨论】:

  • 似乎应该使用简单的表格。你有没有试过但没有成功的例子?
  • 您呈现的信息似乎是表格的,因此使用表格来呈现它具有语义意义,并​​且其行为方式也与您在浏览器中描述的方式相同。有什么理由你认为你不应该使用桌子吗?信息不是语义上的表格吗?
  • 这里可以使用 CSS 网格布局吗?
  • CSS Grid 在 IE11 中不可用。 Polyfills 可能存在,但我没有尝试过。有什么建议吗?

标签: javascript html css html-table flexbox


【解决方案1】:

如果您所呈现的信息在语义上确实是表格的,那么使用表格是有意义的,因为它适合您所呈现的信息并且按照您所说的方式工作在浏览器中。

例如:

.target, .target td {
  border: 1px solid #ddd;
}
.special {
  text-align: center;
}
<table class="target">
  <tbody>
    <tr>
      <td>Column width is width of this text</td>
      <td class="special">Row height is height of this text</td>
    </tr>
    <tr>
      <td>Text</td>
      <td>Text</td>
    </tr>
  </tbody>
</table>

注意:您有一个“特殊”单元格,其文本居中而不是左对齐文本;我在上面使用了special 类。


如果信息不是表格,在语义上,您可以使用其他类型的元素来呈现它,并使用 CSS 调整它们的显示特性以获得您想要的呈现。特别是all vaguely-modern browsers support 使用display: tabledisplay: table-rowdisplay: table-cell。 例如:

.target {
  display: table;
}
.row {
  display: table-row;
}
.cell {
  display: table-cell;
}

.target, .target .cell {
  border: 1px solid #ddd;
}
.special {
  text-align: center;
}
<div class="target">
  <div class="row">
    <div class="cell">Column width is width of this text</div>
    <div class="cell special">Row height is height of this text</div>
  </div>
  <div class="row">
    <div class="cell">Text</div>
    <div class="cell">Text</div>
  </div>
</div>

我使用了rowcell 类,但您也可以使用结构选择器。

【讨论】:

  • 谢谢。从评论中回答您的问题:实际形式是表格,如示例中所示。我认为不使用 table 的原因是因为我读过“tables are bad”。但我想在这种情况下,它实际上是有道理的,数据是表格的。
  • 今天我将检查表是如何工作的。
  • @DonBox:“桌子不好”一直是夸大其词的说法。但这是“用于布局的表格很糟糕。”例如,当内容在语义上不是表格时使用表格。将表格用于在语义上是表格的内容是表格的用途。 :-)
  • 谢谢!是的,确实“表格不适合布局”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-12
  • 1970-01-01
  • 2012-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-17
相关资源
最近更新 更多