【问题标题】:CSS flex get the same behaivor as tableCSS flex 获得与 table 相同的行为
【发布时间】:2017-12-16 22:59:15
【问题描述】:

我正在尝试使用 flexbox 来获得与表格相同的行为。例如:

<div>
    <div class="flex row">
        <p>Short text</p>
        <p>Text </p>
    </div>

    <div class="flex row">
        <p>Very long text</p>
        <p>Text </p>
    </div>
</div>

如何让行与表格位于同一垂直线上?

所以基本上我正在尝试使用 flexbox 实现以下结果

<table>
    <tr>
        <td>Short text</td>
        <td>Text</td>
    </tr>
    <tr>
        <td>Very long text</td>
        <td>Text</td>
    </tr>
</table>

【问题讨论】:

  • 你不能。 Flexbox 不是这样工作的。请改用 CSS 表格。
  • 这是事实吗?
  • 是的......它是。如果你想要表格行为,请使用 CSS 表格布局。
  • 查看 CSS 网格布局:mozilla.org/en-US/developer/css-grid.
  • 要使用 flexbox 执行此操作,您需要使用 flex 列,而不是行。

标签: css html-table flexbox


【解决方案1】:

鉴于您的 HTML 结构,不使用 flexbox。

如果您想要使用 div 的表格行为,请使用 CSS Tables

给你一个比较。

table {
  border-collapse: collapse;
  margin-bottom: 1em;
}

td {
  border: 1px solid grey;
  padding: 1em;
  background: lightgreen;
}

.table {
  display: inline-table;
}

.row {
  display: table-row;
}

p {
  display: table-cell;
  padding: 1em;
  border: 1px solid grey;
  background: lightblue;
}
<table>
  <tr>
    <td>Short text</td>
    <td>Text</td>
  </tr>
  <tr>
    <td>Very long text</td>
    <td>Text</td>
  </tr>
</table>

<div class="table">
  <div class="row">
    <p>Short text</p>
    <p>Text </p>
  </div>

  <div class="row">
    <p>Very long text</p>
    <p>Text </p>
  </div>

  <div>

【讨论】:

  • 两者有什么区别?只有标记?
  • 基本上是的。
  • 所以我不能用flexbox来得到同样的效果?
  • 没有。除非您设置宽度,否则 Flexbox 无法使行之间的宽度相等。
【解决方案2】:

.row {
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.row p { width: 100% }
<div class="table">
  <div class="flex row">
    <p>Short text</p>
    <p>Text </p>
  </div>
  <div class="flex row">
    <p>Very long text</p>
    <p>Text </p>
  </div>
</div>

【讨论】:

  • 结果和表格不一样。线条不直。
  • 您需要在解决方案中定义宽度。在表格解决方案中,它可以正常工作。
  • 您的表格示例中没有宽度。
  • 我的意思是在你的解决方案中你定义了一个宽度。
猜你喜欢
  • 2020-12-09
  • 2017-08-11
  • 2020-12-08
  • 2018-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-10
  • 1970-01-01
相关资源
最近更新 更多