在做小程序的时候,要实现下面的搜索历史界面
下面的搜索很明显的想到是用 flex 布局,然后把 justify-content 设置为 justify-content: flex-start;
代码如下:
1 | <!--wxml--> |
2 | <view class="flex"> |
3 | <button class="item">1</button> |
4 | <button class="item">2</button> |
5 | <button class="item">3</button> |
6 | <button class="item">4</button> |
7 | <button class="item">5</button> |
8 | <button class="item">6</button> |
9 | <button class="item">7</button> |
10 | </view> |
11 | |
12 | |
13 | <!--wxss--> |
14 | .flex{ |
15 | display: flex; |
16 | flex-wrap: wrap; |
17 | justify-content: flex-start; |
18 | } |
19 | .flex .item{ |
20 | width: 216rpx; |
21 | background-color: red; |
22 | margin-bottom: 34rpx; |
23 | } |

可效果却不尽人意,发现 justify-content 不起作用,无论怎么设置都是 space-around 的效果。
经过排查,发现原因是小程序 button 中的默认样式中的margin-left: auto;margin-right: auto;所引起的。
flex 格式化上下文中,在通过 justify-content 和 align-self 进行对齐之前,任何正处于空闲的空间都会分配到该方向的自动 margin 中去。参考自探秘 flex 上下文中神奇的自动 margin
原因找到了,具体修改就容易多了,我们可以覆盖 button 的 margin-left 和 margin-right 的默认值,或者在 button 外面包裹一层 view。
在遇到这个问题之前,我也没想到过 flex 和 margin 之间还能这么用,涨姿势了