css如何实现n宫格布局
前端  /  管理员 发布于 7年前   426
设计思路(无关你是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:flexflex-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宫格布局的详细内容,更多请关注其它相关文章!
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号