html - 在表头 <th> 元素上使用 flexbox

标签 html css flexbox

我有一个场景需要表头内的复杂布局 <th>元素。我想通过制作 <th> 来解决这个问题元素是一个 flex 容器。

但是,如果我从这个最小的例子开始

enter image description here

并更改 <th>元素 display: inline-flex ,表格变为:

enter image description here

即,标题的列宽不再与 <td> 的列宽匹配元素。

如何在标题内使用 flexbox 而不会弄乱列渲染?

编辑以阐明用例:我的 <th>元素最终将包含多个元素,左+右对齐(类似于 this question )。此外,我希望能够控制拉伸(stretch)行为(这就是为什么 flexbox 而不是 float )。


示例 jsfiddle :

<table>
  <thead>
    <tr>
      <th class="column-header">A</th>
      <th class="column-header">B</th>
      <th class="column-header">C</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Something</td>
      <td>Something</td>
      <td>Something</td>
    </tr>
  </tbody>
</table>
table, th, td {
  border: 1px solid #000;
}

.column-header {
  display: inline-flex;
}

最佳答案

My elements will eventually contain multiple elements, with left+right alignment. In addition I want to be able to control the stretch behavior (that's why flexbox instead of just floats).

在那种情况下,您需要在每个 th 中使用 div 并 flex that。

table,
th,
td {
  border: 1px solid #000;
}

.column-header div {
  display: flex;
  justify-content: space-between;
}
<table>
  <thead>
    <tr>
      <th class="column-header">
        <div><span>A</span><span>A</span></div>
      </th>
      <th class="column-header">
        <div><span>B</span><span>B</span></div>
      </th>
      <th class="column-header">
        <div><span>C</span><span>C</span></div>
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Something</td>
      <td>Something</td>
      <td>Something</td>
    </tr>
  </tbody>
</table>

关于html - 在表头 <th> 元素上使用 flexbox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56685222/

相关文章:

html - 2 使用 Flex 的图像旁边的元素

html - 如何使用 CSS/HTML 制作 Facebook 封面?

css - 并排对齐2个div

css - 如何摆脱这个滚动条?

css - 是否可以将某些 CSS 仅应用于禁用 Javascript 的用户?

html - 你如何将元素放在新行上,与 css-grid 相同的列?

jQuery 更改单击图像的图像 onclick 和其他图像

jquery - 溢出 :scroll prevents slider gif from displaying

CSS - 为什么要添加 -webkit 等到过渡

html - 显示类型被未知来源覆盖