首页 > 解决方案 > 如何使用 css 网格在第一行居中 1 列并将其他 3 列放在第二行?

问题描述

我是 CSS 网格的新手。我有一个 div,里面有 4 个 div,如代码所示。我希望将第一个内部 div 放置在行的中心。第二排剩下的3个孩子。

我尝试了一些基本的 css 样式来让这些孩子放在正确的位置。但我希望有更好的方法来做到这一点。

<style>
.parent {
   width: 100%;
   display: grid;
   grid-template-columns: repeat: (3, 1fr)
}
</style>
<div class="parent">
    <div class="child">1</div>
    <div class="child">2</div>
    <div class="child">3</div>
    <div class="child">4</div>
</div>

我希望得到如下所示的结果:http: //prntscr.com/orr41c

标签: htmlcsscss-grid

解决方案


这是我所做的:

/* first child goes in the first row / second column and span 1 column */

.parent .child:nth-of-type(1) {
    grid-column: 2/ span 1;
    grid-row: 1;
    background: red;
  }

  /* the 3 other children place themselves in the second row */

  .parent .child:nth-of-type(n+2) {
    grid-row: 2;
  }

<style>
  .parent {
    width: 150px;
    height: 100px;
    display: grid;
    grid-template-columns: repeat: (3, 1fr);
    margin: 0 auto;
  }
  
  .parent .child {
    background: yellow;
    width: 100%;
    height: 100%;
  }
  
  .parent .child:nth-of-type(1) {
    grid-column: 2/ span 1;
    grid-row: 1;
    background: red;
  }
  
  .parent .child:nth-of-type(n+2) {
    grid-row: 2;
  }
</style>
<div class="parent">
  <div class="child">1</div>
  <div class="child">2</div>
  <div class="child">3</div>
  <div class="child">4</div>
</div>


推荐阅读