【问题标题】:Center CSS 2nd row of lis that is spread evenly under a div using display:table居中 CSS 的第二行 lis 使用 display:table 均匀分布在 div 下
【发布时间】:2016-09-03 09:00:20
【问题描述】:

我想将我的lis 均匀地分布在一个列表下,所以我使用了display:table 技巧,但这只有在你只有一排展开的项目时才有用。从下图中可以看出,如果有 2 行,则第 2 行的项目将保持与第一行相同的宽度,这很好,但不再居中。如何让它居中? lis 的数量会动态变化,因此理想情况下,如果有超过 3 个 li,它会创建一个新行,并在必要时将第 2 行的 li(s) 居中。

HTML

<ul class="table">
  <div class="table-row">
    <li class="cell type type-water">water</li>
    <li class="cell type type-ghost">ghost</li>
    <li class="cell type type-ground">ground</li>
  </div>
  <div class="table-row">
    <li class="cell type type-ice">ice</li>
  </div>
</ul>

CSS

.table {
  display: table;
  width: 100%;
  list-style: none;
    table-layout: fixed;
}

.table-row {
  display: table-row;
  width: 100%;
  list-style: none;
    table-layout: fixed;
}

.cell {
  display: table-cell;
  text-align: center;
}

【问题讨论】:

  • 您的列表无效。 div 不能是ul 的子代,而li 只能出现在ulol 中。

标签: html css alignment center


【解决方案1】:

一般来说,您无法正确居中。表格以表格方式显示。它有列和行,必须保持对齐。

例如,如果您的第一行有 3 个单元格,而第二行有 2 个单元格,您可以将最后 2 个单元格左对齐或右对齐,但不能居中。

因此,我建议让细胞生长而不是居中

.table-row {
  display: table;
  width: 100%;
  list-style: none;
  table-layout: fixed;
}
.cell {
  display: table-cell;
  text-align: center;
}
.table, .cell {
  border: 1px solid;
}
<div class="table">
  <div class="table-row">
    <div class="cell type type-water">water</div>
    <div class="cell type type-ghost">ghost</div>
    <div class="cell type type-ground">ground</div>
  </div>
  <div class="table-row">
    <div class="cell type type-ice">ice</div>
  </div>
</div>

您可以这样做,因为现在每行中单元格的宽度是独立的,我们实际上可以将每一行包装在不同的表格中。

或者,您可以手动插入元素或伪元素以将单元格放置在所需位置:

.table {
  display: table;
  width: 100%;
  table-layout: fixed;
  border-collapse: collapse;
}
.table-row {
  display: table-row;
}
.cell {
  display: table-cell;
  text-align: center;
  border: 2px solid;
}
.insert-before::before, .insert-after::after {
  content: '';
  display: table-cell;
}
<div class="table">
  <div class="table-row">
    <div class="cell type type-water">water</div>
    <div class="cell type type-ghost">ghost</div>
    <div class="cell type type-ground">ground</div>
  </div>
  <div class="table-row insert-before insert-after">
    <div class="cell type type-ice">ice</div>
  </div>
</div>

但是如果不同行的单元格数量有不同的奇偶性,你将无法实现居中。

【讨论】:

    猜你喜欢
    • 2011-03-16
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多