CSS 等高列

Equal height columns with CSS

我想为我的 css table 使用百分比。不幸的是,它对我不起作用。

这段代码有什么问题?我应该使用 flexbox 而不是 table 吗?

我想使用 table,因为我想要相同高度的列。

ul {
  list-style: none;
  margin: 0;
  display: table;
  table-layout: fixed;
  width: 100%;
}

li {
  width: 50%;
  display: table-cell;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
</ul>

带 Flexbox 的等高列

HTML

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
</ul>

CSS

ul { display: flex; }

使用上面的简单代码,您可以在列表项中放置任意数量的内容,并且所有列表项的高度都相同。

DEMO


备注:

  • 弹性容器的初始设置是flex-direction: row,这意味着子元素(又名弹性项目)将水平排列。

  • flex 容器的另一个初始设置是 align-items: stretch,这会导致 flex 项目展开整个容器的高度(或宽度,取决于 flex-direction)。

  • 以上两个设置共同创建等高列。

  • 弹性等高列仅适用于兄弟姐妹。

  • 将高度应用于弹性项目会覆盖等高功能。

  • .


浏览器支持: 所有主流浏览器都支持Flexbox,except IE < 10. Some recent browser versions, such as Safari 8 and IE10, require vendor prefixes. For a quick way to add prefixes use Autoprefixer. More details in .

我给出了一个与@Michael_B 不同的问题解释的答案。使用 li 元素上的 width: 50%; 初始样式,我认为期望的结果是让六个列表项流入 2 列和 3 行。这种情况使用 CSS 表无法轻易解决,但使用 flexbox 相对简单。

ul {
  list-style: none;
  margin: 0;
  width: 100%;
  /*kills the irritating intial padding on uls in webkit*/
  -webkit-padding-start: 0;
  display: flex;
  flex-flow: row wrap;
  /*stretch is the default value, but it will force items to stretch to match others in their row*/
  align-items: stretch;
  /*below properties just emphasize the layout*/
  padding: 2px;
  background-color: green;
}
li {
  /*forces border-width and padding to be part of the declared with (50% in this case)*/
  box-sizing: border-box;
  width: 50%;
  /*list-item, inline-block, and block work equally well*/
  display: list-item;
  /*below properties just emphasize the layout*/
  border: white 2px solid;
  background-color: lightgreen;
}
/*I set this property to show what happens if 1 item has a different height*/

li:nth-child(3) {
  height: 40px;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
</ul>

这是一个使用 ul/li 元素的示例,2 列使用百分比且高度相等。

由于表格更喜欢 table/row/cell 布局,我稍微调整了您的 html 结构。

* {
    margin: 0;
}
html, body {
    height: 100%;
}
.table {
  display: table;
  width: 90%;
  height: 60%;
  padding-top: 5%;
  margin: 0 auto;
}
ul {
  display: table-row;
  list-style: none;
  margin: 0;
}

li {
  display: table-cell;
  width: 50%;
  border: 1px solid #999;
}
<div class="table">
  <ul>
    <li>1</li>
    <li>2</li>
  </ul>
  <ul>
    <li>3</li>
    <li>4</li>
  </ul>
  <ul>
    <li>5</li>
    <li>6</li>
  </ul>
</div>