小编典典

如何右对齐弹性项目?

all

是否有比使用更灵活的方式来右对齐“联系人” 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>

http://jsfiddle.net/vqDK9/


阅读 175

收藏
2022-03-01

共1个答案

小编典典

更灵活的方法是使用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>
2022-03-01