网格布局内的中心列

时间:2019-03-16 17:40:28

标签: html css css3 flexbox css-grid

我已经开始学习网格系统(display:grid),并且我有以下代码,但是我不知道如何在不向grid-template-columns添加更多列的情况下居中最后两列(4和5)并在各列中使用grid-column-start和grid-column-end。有可能吗?:

HTML:

<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>

CSS:

body {
    margin: 0;
}

.grid-container {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-gap: 20px;
}

.grid-item {
    padding: 10px;
    background: skyblue;
}

JSFiddle:https://jsfiddle.net/3b5Lxujh/

我所拥有的:

What I have

我想要的:

What I want

1 个答案:

答案 0 :(得分:2)

如果您使用的是CSS网格,则应添加列-为此,您使用grid-template-columns: repeat(6, 1fr)使用6列网格,每个项目跨越两个网格列-和 place < / em>使用grid-column规则到中心的最后一行-请参见下面的演示

body {
  margin: 0;
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  grid-gap: 20px;
}

.grid-item {
  padding: 10px;
  background: skyblue;
  grid-column: span 2;
}

.grid-item:nth-last-child(2) {
  grid-column: 2 / 4;
}

.grid-item:last-child {
  grid-column: 4 / 6;
}
<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>


Flexbox解决方案

对于这种布局, flexbox 更适合-通常我会使用flex-basis(带有calc的flexbox来创建网格间隙)像这样:

body {
  margin: 0;
}

.grid-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.grid-item {
  padding: 10px;
  background: skyblue;
  margin: 10px;
  flex-basis: calc(33.33% - 40px);
}
<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>