首頁  >  文章  >  web前端  >  css如何實現n宮格佈局

css如何實現n宮格佈局

王林
王林轉載
2020-03-12 10:52:592611瀏覽

css如何實現n宮格佈局

設計思路(無關你是scss還是less)

1、為了方便內部元素水平/垂直居中, 整體我們用flex佈局.

2、使用方形佔位, 因為用了padding-top:100%, 所以我們就需要再單獨用一個div來裝內容, 我給他起名"item__content".

3、為了讓內容的容器div充滿方塊, 我們給他設定樣式:position:absolute;top:0;left:0;right:0;bottom:0;;

(推薦教學:CSS入門教學

HTML程式碼

<!-- 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程式碼

為了不冗餘, 我把公共的部分抽離的出來起名".a-grid";

mixin支援4個參數, 分別是$row(行數), $column(列數), $hasBorder(是否有邊框), $isSquare(是否保證每個區塊是正方形).

#mixin內部透過計算並結合:nth-child實現"整體無外邊框"的效果

.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;
            }
        }
    }
}

使用

// 生成一个 3行3列, 正方形格子的宫格
.a-grid-3-3 {
    @include grid(3, 3, true);
}
 
// 生成一个 2行5列, 无边框宫格, 每个格子由内容决定高度
.a-grid-2-5 {
    @include grid(2, 5, false, false);
}

提醒大家: 如要做n x m的佈局, 用@include grid(n, m)後千萬別忘了在html中加入n x m個對應的dom結構。

相關影片教學推薦:css影片教學

#

以上是css如何實現n宮格佈局的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:jb51.net。如有侵權,請聯絡admin@php.cn刪除