居中 flex 项目,行尾有一个 [英] Center flex items with one at the end of the row

查看:15
本文介绍了居中 flex 项目,行尾有一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 flexbox 创建一个导航栏.这是我的 html:

<div>项目</div><div>关于项目</div><div>联系我们</div><div>邮箱</div>

还有我的css:

.container {显示:弹性,对齐内容:中心}

这是目前的样子:

我希望 mailbox div 位于 flex 容器 的末尾.我希望它看起来更像这样.

我在那个 flex 项目上尝试了 flex-end 无济于事.我需要做什么才能做到这一点?

解决方案

布局可以通过 flex auto 边距和一个不可见的 flex item 来实现.

.container {显示:弹性;}.container >div:第一个孩子{右边距:自动;可见性:隐藏;}.container >div:最后一个孩子{左边距:自动;}

<div>邮箱</div><!-- 不可见的弹性项目--><div>项目</div><div>关于项目</div><div>联系我们</div><div>邮箱</div>

jsFiddle

注意事项:

  • Flex auto边距用于对齐 flex项.
  • 由于 flexbox 对齐是通过在容器中分配自由空间来工作的,因此添加了一个不可见的 flex 项以在两侧创建相等的平衡.
  • 虚拟项目与最后一个项目(邮箱)的宽度完全相同很重要.否则,不会有均等的平衡,中间的项目也不会完美居中.

在此处了解更多信息:对齐 Flex 项目的方法

I am creating a navbar with flexbox. Here is my html:

<div class="container">
    <div>Project</div>
    <div>About the Project</div>
    <div>Contact Us</div>
    <div>Mailbox</div>
</div>

And my css:

.container {
  display: flex,
  justify-content: center
}

Here is what it currently looks like:

I want the mailbox div to be at the end of the flex container. I want it to look more like this.

I have tried flex-end on that flex item to no avail. What do I need to do to make that happen?

解决方案

The layout can be achieved with flex auto margins and an invisible flex item.

.container {
  display: flex;
}
.container > div:first-child {
  margin-right: auto;
  visibility: hidden;
}
.container > div:last-child {
  margin-left: auto;
}

<div class="container">
  <div>Mailbox</div><!-- invisible flex item -->
  <div>Project</div>
  <div>About the Project</div>
  <div>Contact Us</div>
  <div>Mailbox</div>
</div>

jsFiddle

Notes:

  • Flex auto margins are used for aligning the flex items.
  • Since flexbox alignment works by distributing free space in the container, an invisible flex item is added to create equal balance on both sides.
  • It's important that the phantom item be exactly the same width as the last item (Mailbox). Otherwise, there won't be equal balance and the middle items will not be perfectly centered.

Learn more here: Methods for Aligning Flex Items

这篇关于居中 flex 项目,行尾有一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆