常見應用場景
現在的APP界面基本都是大同小異, 宮格布局現在基本成了每個APP必然的存在.
帶邊框, 常用在"功能導航"頁面
無邊框, 常用在首頁分類
設計目標
在scss環境下, 通過mixin實現n宮格, 并且可以支持"有無邊框"和"每個格是否正方形":
@include grid(3, 3, true); // 3 x 3, 有邊框, 且每個格為正方形@include grid(2, 5, false, false); // 2 x 5, 無邊框
最終效果
"padding百分比"小技巧
先解釋一個小技巧, 如何實現正方形, 保證看一遍就會, 結論就是:
padding的值如果是百分比, 那么他是相對"父"元素寬度計算的, 也就是說如果"父"元素寬度是100px, "子"元素設置padding-top:100%,"子"元素的padding-top實際上等于100px, 這樣就實現了一個正方形(100 x 100). 為了減少干擾, 我們把"子"元素高度設置為0;
設計思路(無關你是scss還是less)
因此我們的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>
代碼(scss)
這里做了3件事:
.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樣式庫, 目標是兼容小程序, 大家有興趣的可以一起玩, 這是本節課對應的源碼:
https://github.com/any86/3a.css/blob/develop/src/components/_grid.scss
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答