让前端飞微信小程序开发ios

当小程序的flex布局遇到button时,justify-con

2019-10-14  本文已影响0人  lkkwxy

当小程序的flex布局遇到button时,justify-content不起作用的原因及解决方案

在做小程序的时候,要实现下面的搜索历史界面


屏幕快照 2019-10-14 上午10.20.07.png

下面的搜索很明显的想到是用flex布局,然后把justify-content设置为justify-content: flex-start;
代码如下:

<!--wxml-->
<view class="flex">
<button class="item">1</button>
<button class="item">2</button>
<button class="item">3</button>
<button class="item">4</button>
<button class="item">5</button>
<button class="item">6</button>
<button class="item">7</button>
</view>


<!--wxss-->
.flex{
  display: flex;
  flex-wrap: wrap; 
  justify-content: flex-start;
}
.flex .item{
  width: 216rpx;
  background-color: red;
  margin-bottom: 34rpx;
}
屏幕快照 2019-10-14 上午10.35.32.png

可效果却不尽人意,发现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之间还能这么用,涨姿势了

上一篇 下一篇

猜你喜欢

热点阅读