css实现n宫格布局封装
# 设计思路:
1,用flex布局,水平垂直居中展示;
2,正方形占位,通过子组件padding百分比;
3,让内容的容器div充满方块,设置绝对布局:position:absolute;top:0;left:0;right:0;bottom:0;
# 使用scss封装:
1,mixin支持4个参数, 分别是row(行数), column(列数), hasBorder(是否有边框), isSquare(是否保证每个块是正方形).
2,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;
}
}
}
}
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
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
# 使用方法
// 生成一个 3行3列, 正方形格子的宫格
.a-grid-3-3 {
@include grid(3, 3, true);
}
// 生成一个 2行5列, 无边框宫格, 每个格子由内容决定高度
.a-grid-2-5 {
@include grid(2, 5, false, false);
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
<!-- a-grid" 布局组件格式 -->
<div class="a-grid">
<!-- a-grid__item用来占位实现正方形 -->
<div class="a-grid__item">
<!-- item__content才是真正装内容的容器 -->
<div class="item__content">
这是一条内容
</div>
</div>
</div>
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
上次更新: 2024/05/30, 10:50:45