使用CSS网格

时间:2019-07-02 13:24:10

标签: css css-grid

我正在尝试实现一个布局,该布局在第一行中具有2个列,在此之后具有3个列,就像附加的图像一样。我正在使用css grid

i want to achieve this layout

到目前为止,这是我的代码

body {
  background: #161616;
  color: #bdbdbd;
  font-weight: 300;
  height: 100vh;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  font-family: Helvetica neue, roboto;
}

h1 {
  font-weight: 300;
}
a {
  color: white;
  text-decoration: none;
  color: #4d4d4d;
}
.container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-column-gap: 15px;
  grid-row-gap: 15px;
}
.feature__item {
  background-color: #C4C4C4;
  padding: 15px;
  color: #4d4d4d;
}

.feature__item:first-of-type{
  grid-column-start: 1;
  grid-column-end: 3;
}

.feature__item:nth-child(2) {
  
}
<div class="container">
  <div class="feature__item">
    <h5>Heading</h5>
    <p>12</p>
    <a href="#" class="btn btn-primary">Discover More</a>
  </div>
  <div class="feature__item">
    <h5>Heading</h5>
    <p>34</p>
    <a href="#" class="btn btn-primary">Discover More</a>
  </div>
  <div class="feature__item">
    <h5>Heading</h5>
    <p>56</p>
    <a href="#" class="btn btn-primary">Discover More</a>
  </div>
  <div class="feature__item">
    <h5>Heading</h5>
    <p>78</p>
    <a href="#" class="btn btn-primary">Discover More</a>
  </div>
  <div class="feature__item">
    <h5>Heading</h5>
    <p>90</p>
    <a href="#" class="btn btn-primary">Discover More</a>
  </div>
</div>

这是Playcode

上的有效示例

1 个答案:

答案 0 :(得分:5)

您需要将网格划分为6列,才能跨越其中的3或2列

body {
  background: #161616;
  color: #bdbdbd;
  font-weight: 300;
  height: 100vh;
  margin: 0;
  display: flex;
  /*
  align-items: center;
  justify-content: center;
  */
  text-align: center;
  font-family: Helvetica neue, roboto;
}

h1 {
  font-weight: 300;
}
a {
  color: white;
  text-decoration: none;
  color: #4d4d4d;
}
.container {
/* instead , align/justify */ margin:auto;
  display: grid;
  grid-template-columns:repeat(6,1fr);
  grid-column-gap: 15px;
  grid-row-gap: 15px;
}
.feature__item {
  background-color: #C4C4C4;
  padding: 15px;
  color: #4d4d4d;
  grid-column : span 2;
}

.feature__item:first-of-type,

.feature__item:nth-child(2) {
  grid-column: span 3;
  
}
<div class="container">
  <div class="feature__item">
    <h5>Heading</h5>
    <p>12</p>
    <a href="#" class="btn btn-primary">Discover More</a>
  </div>
  <div class="feature__item">
    <h5>Heading</h5>
    <p>34</p>
    <a href="#" class="btn btn-primary">Discover More</a>
  </div>
  <div class="feature__item">
    <h5>Heading</h5>
    <p>56</p>
    <a href="#" class="btn btn-primary">Discover More</a>
  </div>
  <div class="feature__item">
    <h5>Heading</h5>
    <p>78</p>
    <a href="#" class="btn btn-primary">Discover More</a>
  </div>
  <div class="feature__item">
    <h5>Heading</h5>
    <p>90</p>
    <a href="#" class="btn btn-primary">Discover More</a>
  </div>
</div>