position: absolute
相比,有没有更多的 flexbox-ish 方式可以使 “Contact” 右对齐?
.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>
更加灵活的方法是使用auto
左页边距(与在块格式化上下文中使用时相比,灵活项对自动页边距的处理有些不同)。
.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>
干得好。在 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>
如果要为此使用 flexbox,则应该能够这样做(在容器上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 上的演示,可让您快速尝试上述操作。