如何每行显示三列?

时间:2014-06-13 02:57:07

标签: html css html5 css3 flexbox

我一直试图每行显示三列。是否可以使用flexbox?

我目前的CSS是这样的:

.mainDiv {
    display: flex;
    margin-left: 221px;
    margin-top: 43px;
}

此代码将所有内容放在一行中。 我想添加一个约束来显示每行三个记录。

3 个答案:

答案 0 :(得分:92)

这可能是您正在寻找的:

http://jsfiddle.net/L4L67/

body>div {
  background: #aaa;
  display: flex;
  flex-wrap: wrap;
}

body>div>div {
  flex-grow: 1;
  width: 33%;
  height: 100px;
}

body>div>div:nth-child(even) {
  background: #23a;
}

body>div>div:nth-child(odd) {
  background: #49b;
}
<div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

答案 1 :(得分:7)

尽管以上答案似乎是正确的,但我还是想添加一个(希望)更具可读性的示例,该示例也以3列的形式保留在不同的宽度上:

.flex-row-container {
    background: #aaa;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: center;
}
.flex-row-container > .flex-row-item {
    flex-grow: 1;
    flex: 1 1 30%;
    height: 100px;
}

.flex-row-item {
  background-color: #fff4e6;
  border: 1px solid #f76707;
}
<div class="flex-row-container">
  <div class="flex-row-item">1</div>
  <div class="flex-row-item">2</div>
  <div class="flex-row-item">3</div>
  <div class="flex-row-item">4</div>
  <div class="flex-row-item">5</div>
  <div class="flex-row-item">6</div>
</div>

希望这对其他人有帮助。

答案 2 :(得分:0)

使用“网格布局”尝试这一操作:

.grid-container {
  display: grid;
  grid-template-columns: auto auto auto;
  padding: 10px;
}
.grid-item {
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(0, 0, 0, 0.8);
  padding: 20px;
  font-size: 30px;
  text-align: center;
}
<div class="grid-container">
  <div class="grid-item">1</div>
  <div class="grid-item">2</div>
  <div class="grid-item">3</div>  
  <div class="grid-item">4</div>
  <div class="grid-item">5</div>
  <div class="grid-item">6</div>  
  <div class="grid-item">7</div>
  <div class="grid-item">8</div>
  <div class="grid-item">9</div>  
</div>