对齐Flex项目?

是否有更多的flexbox-ish的方式来正确对齐“联系”比使用position: absolute

.main { display: flex; }
.a, .b, .c { background: #efefef; border: 1px solid #999; }
.b { flex: 1; text-align: center; }
.c { position: absolute; right: 0; }
<h2>With title</h2>
<div class="main">
    <div class="a"><a href="#">Home</a></div>
    <div class="b"><a href="#">Some title centered</a></div>
    <div class="c"><a href="#">Contact</a></div>
</div>
<h2>Without title</h2>
<div class="main">
    <div class="a"><a href="#">Home</a></div>
    <!--<div class="b"><a href="#">Some title centered</a></div>-->
    <div class="c"><a href="#">Contact</a></div>
</div>

干得好。 在flex容器上设置justify-content: space-between

.main { 
    display: flex; 
    justify-content: space-between;
  }
.a, .b, .c { background: #efefef; border: 1px solid #999; }
.b { text-align: center; }
<h2>With title</h2>
<div class="main">
    <div class="a"><a href="#">Home</a></div>
    <div class="b"><a href="#">Some title centered</a></div>
    <div class="c"><a href="#">Contact</a></div>
</div>
<h2>Without title</h2>
<div class="main">
    <div class="a"><a href="#">Home</a></div>
<!--     <div class="b"><a href="#">Some title centered</a></div> -->
    <div class="c"><a href="#">Contact</a></div>
</div>

更灵活的方法是使用auto左边距(flex项目对待自动边距与在块格式化上下文中使用时略有不同)。

.c {
    margin-left: auto;
}

更新小提琴:

.main { display: flex; }
.a, .b, .c { background: #efefef; border: 1px solid #999; }
.b { flex: 1; text-align: center; }
.c {margin-left: auto;}
<h2>With title</h2>
<div class="main">
    <div class="a"><a href="#">Home</a></div>
    <div class="b"><a href="#">Some title centered</a></div>
    <div class="c"><a href="#">Contact</a></div>
</div>
<h2>Without title</h2>
<div class="main">
    <div class="a"><a href="#">Home</a></div>
    <!--<div class="b"><a href="#">Some title centered</a></div>-->
    <div class="c"><a href="#">Contact</a></div>
</div>
<h1>Problem</h1>
<p>Is there a more flexbox-ish way to right align "Contact" than to use position absolute?</p>

如果你想为此使用flexbox,你应该可以这样做( display: flex在容器上flex: 1 ,在项目上display: flex flex: 1 ,在.c上显示text-align: right ):

.main { display: flex; }
.a, .b, .c {
  background: #efefef;
  border: 1px solid #999;
  flex: 1;
}
.b { text-align: center; }
.c { text-align: right; }

...或者(更简单),如果项目不需要满足,可以在容器上使用justify-content: space-between并完全删除text-align规则:

.main { display: flex; justify-content: space-between; }
.a, .b, .c { background: #efefef; border: 1px solid #999; }

这是一个Codepen的演示,可以让你快速的尝试上面的内容。

链接地址: http://www.djcxy.com/p/75673.html

上一篇: align flex item?

下一篇: center align a div with inline