居中
在 flexbox 布局和 auto margin 合作的例子中最简单的就是元素居中。
See the Pen Flexbox Layout with auto margin - center element by Lien (@movii) on CodePen.
分隔区块
例一
想象的场景是页面顶部常见而又千变万化的 header 区块,在容器中的 item 身上使用 margin[-*]: auto
来达到布局目标。
See the Pen Flexbox Layout with auto margin by Lien (@movii) on CodePen.
例二
See the Pen Flexbox Layout with auto margin - 4 by Lien (@movii) on CodePen.
例三
See the Pen Flexbox Layout with auto margin - 5 by Lien (@movii) on CodePen.
例四
See the Pen Flexbox Layout with auto margin - 7 by Lien (@movii) on CodePen.
将元素置于角落
See the Pen Flexbox Layout with auto margin - 10 by Lien (@movii) on CodePen.
在一个 item 已经居中的情况下,在该元素到容器距离之间再插入、并且居中一个元素
这里使用的方法其实并不是非常语义化,看上去虽然实现了需求,实际上和上面所有 item 上设置 margin-left: auto
和在 :last-child
上加上 margin-right: auto
的方式一致,只是将 :last-child
本身 visibility: hidden
掉了。
See the Pen Flexbox Layout with auto margin - 8 by Lien (@movii) on CodePen.
容器中如果边上有不规则长度 siblings 仍保持居中
使用绝对定位
不论是不是 flexbox 布局容器中,一个元素只要是 position: absolute
就会脱离文档流,在这第一种方法里,使用情况上最好是左右不规则长度的 siblings 是规定长度、十分肯定不会和当中的 position: absolute
的居中元素发生相互遮挡的可能性。
水平方向
See the Pen Flexbox Layout with auto margin - 11 by Lien (@movii) on CodePen.
垂直方向
See the Pen Flexbox Layout with auto margin - 12 by Lien (@movii) on CodePen.
使用 flexbox 容器嵌套 flexbox 容器
另一种方式是 flexbox 容器嵌套 flexbox 容器,或者说把原来子级的 .item
也设置成 flexbox 容器,在其中再加一个 span
作为内容。
- 顶层的
.contain
是一个 flexbox 容器; - 每一个子级的
.item
此时是一个 flex item; - 每一个
.item
使用flex: 1
来获得容器的平均分配空间; - 再次设置
.item
为display: flex
将其也设置成为 flex 容器; - 此时
.item
中的span
成了 flex item; - 在
span
上分配 auto margin 来获得左侧左对齐、右侧右对齐的效果。
See the Pen Flexbox Layout with auto margin - 13 by Lien (@movii) on CodePen.
技术发展迭代很快,所以这些笔记内容也有类似新闻的时效性,不免有过时、或者错误的地方,欢迎指正 ^_^。
BEST
Lien(A.K.A 胡椒)