本文摘自PHP中文网,作者V,侵删。

设计思路(无关你是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代码
1 2 3 4 5 6 7 8 9 10 | < div class = "a-grid" >
< div class = "a-grid__item" >
< div class = "item__content" >
内容...
</ div >
</ div >
</ div >
|
CSS代码
为了不冗余, 我把公共的部分抽离的出来起名".a-grid";
mixin支持4个参数, 分别是$row(行数), $column(列数), $hasBorder(是否有边框), $isSquare(是否保证每个块是正方形).
mixin内部通过计算并结合:nth-child实现"整体无外边框"的效果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | .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 ;
}
}
}
}
|
使用
1 2 3 4 5 6 7 8 9 | // 生成一个 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宫格布局的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
css哪些属性可以继承
css outline-offset属性怎么用
css里面div如何居中显示文字
css怎么设置左边距
css如何做三角形
css写在html里面吗?
css是编程语言吗
css设置字体大小的属性名是什么
移动端全景装修图的实现实例分享
css如何实现波浪效果
更多相关阅读请进入《css》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » css如何实现n宫格布局