Design ideas (regardless of whether you are scss or less)
1. In order to facilitate the horizontal/vertical centering of internal elements, we use flex layout as a whole.
2. Use a square placeholder. Because padding-top:100% is used, we need to use a separate div to hold the content. I named it "item__content".
3. In order to make the content The container div is filled with squares, and we set the style for it: position:absolute;top:0;left:0;right:0;bottom:0;;
(Recommended tutorial: CSS Getting Started Tutorial)
HTML code
<!-- a-grid是一个flex容器, 方便他的内容做"水平/垂直居中" --> <div class="a-grid"> <!-- a-grid__item用来占位实现正方形 --> <div class="a-grid__item"> <!-- item__content才是真正装内容的容器 --> <div class="item__content"> 内容... </div> </div> </div>
CSS code
In order not to be redundant, I extracted the common part and named it ".a-grid";
mixin supports 4 parameters, namely $row (number of rows), $column (number of columns), $hasBorder (whether there is a border), $isSquare (whether each block is guaranteed to be square).
mixin internally calculates and combines: nth-child to achieve the effect of "overall no outer border"
.a-grid { display: flex; flex-wrap: wrap; width: 100%; .a-grid__item { text-align:center; position:relative; >.item__content { display:flex flex-flow: column; align-items: center; justify-content: center; } } } @mixin grid($row:3, $column:3, $hasBorder:false, $isSquare:true) { @extend .a-grid; .a-grid__item { flex-basis: 100%/$column; @if($isSquare) { padding-bottom: 100%/$column; height: 0; } >.item__content { @if($isSquare) { position:absolute; top:0;left:0;right:0;bottom:0; } } } @for $index from 1 to (($row - 1) * $column + 1) { .a-grid__item:nth-child(#{$index}) { @if($hasBorder) { border-bottom: 1px solid #eee; } } } @for $index from 1 to $column { .a-grid__item:nth-child(#{$column}n + #{$index}) { @if($hasBorder) { border-right: 1px solid #eee; } } } }
Use
// 生成一个 3行3列, 正方形格子的宫格 .a-grid-3-3 { @include grid(3, 3, true); } // 生成一个 2行5列, 无边框宫格, 每个格子由内容决定高度 .a-grid-2-5 { @include grid(2, 5, false, false); }
Remind everyone: If you want to make an n x m layout, use After @include grid(n, m), don’t forget to add n x m corresponding dom structures in html.
Recommended related video tutorials: css video tutorial
The above is the detailed content of How to implement n-square layout in css. For more information, please follow other related articles on the PHP Chinese website!