javascript - 使用 table 或 flexbox 创建类似网格的 UI

标签 javascript html css html-table flexbox

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

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

我可以用 flex-box 还是只用旧的 table 来做这个? 有例子吗?

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

enter image description here

最佳答案

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

例如:

.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>

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


如果信息不是表格,在语义上,您可以使用其他类型的元素来呈现它,并使用 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 类,但您也可以使用结构选择器。

关于javascript - 使用 table 或 flexbox 创建类似网格的 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45419218/

相关文章:

css - 这个具有多个类的 CSS 是否可以进一步简化?

javascript - AngularJS UI 路由器的 "resolve"触发两次

javascript - 从 WP API 传递一个值来做 Vue href?

javascript - 使用数组存储多个ID或类,然后在函数中操作它们

java - 查看 JSP 站点中的时间戳是否超过 24 小时

jquery - 不同定位的列 css

javascript - 嵌套解析 promise 之外的空数组

html - 是 HTML 5 + CSS 3 >= Microsoft Silverlight

javascript - 确定正在使用的浏览器,然后根据该设置类的样式

html - 为什么我不能在 div 中将此图像居中?