笔记:Flexbox 中使用 auto margin 的技巧


居中

在 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 作为内容。

  1. 顶层的 .contain 是一个 flexbox 容器;
  2. 每一个子级的 .item 此时是一个 flex item;
  3. 每一个 .item 使用 flex: 1 来获得容器的平均分配空间;
  4. 再次设置 .itemdisplay: flex 将其也设置成为 flex 容器;
  5. 此时 .item 中的 span 成了 flex item;
  6. span 上分配 auto margin 来获得左侧左对齐、右侧右对齐的效果。

See the Pen Flexbox Layout with auto margin - 13 by Lien (@movii) on CodePen.

感谢阅读

你们好, 2018 年初把小站从 Jekyll 迁移到 Hugo 的过程中,删除了评论区放的 Disqus 插件,考虑有二:首先无论评论、还是对笔记内容的进一步讨论,读者们更喜欢通过邮件、或者 Twitter 私信的方式来沟通;其次一年多以来 Disqus 后台能看到几乎都是垃圾留言(spam),所以这里直接贴一下邮件、以及 Twitter 账户 地址。

技术发展迭代很快,所以这些笔记内容也有类似新闻的时效性,不免有过时、或者错误的地方,欢迎指正 ^_^。

BEST
Lien(A.K.A 胡椒)
本站总访问量 本站总访客量 本文总阅读量