原来一直使用flex布局来实现水平垂直居中,今天才知道还有grid也是很好用的,参考阮一峰大神的博客,简单记录一下学习;
<div class="container"> <div class="item">1</div><div class="item">2</div><div class="item">3</div><div class="item">4</div><div class="item">5</div><div class="item">6</div><div class="item">7</div><div class="item">8</div></div>
.container {display: grid;/* grid-template-columns属性定义每一列的列宽,grid-template-rows属性定义每一行的行高。 */grid-template-columns: repeat(4, 60px);grid-template-rows: repeat(2, 60px);/* grid-gap属性是grid-column-gap和grid-row-gap的合并简写形式, grid-row-gap属性设置行与行的间隔(行间距),grid-column-gap属性设置列与列的间隔(列间距)我设置的是10 行与行之间 列与列之间 都是10*/grid-gap: 10px;/* item在这个单元格中的位置justify-items属性设置单元格内容的水平位置(左中右),align-items属性设置单元格内容的垂直位置(上中下) */align-items: center;justify-items: center; /* justify-content属性是整个内容区域在容器里面的水平位置(左中右),align-content属性是整个内容区域的垂直位置(上中下)。 */justify-content: center;align-content: center;width: 100%;height: 500px;background: #f3f3f3;}.item {width: 30px;height: 30px;display: grid;border: 1px solid red;justify-content: center;align-content: center;}
关于 justify-content: center; align-content: center; justify-content是控制整个内容区域在container中的位置的
align-items: center; justify-items: center;简单来说-items是控制单个单元格的位置的
这是未设置任何center的状态
这是设置了 justify-content: center; align-content: center;
可以看到整体居中了 但是每个div在自己所在的单元格内还是处在左上角的位置的
这里设置里align-items: center; justify-items: center;,单元格内就居中了
3.一般情况下需要item中的文字也水平垂直 所以我给item也设置了grid 就可以实现了
ps:如果没有设置 就会是下面的情况
参考 /blog//03/grid-layout-tutorial.html