How to Right-align flex item?
A more flex approach would be to use an auto
left margin (flex items treat auto margins a bit differently than when used in a block formatting context).
.c {
margin-left: auto;
}
Updated fiddle:
.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>
Here you go. Set justify-content: space-between
on the flex container.
.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>
You can also use a filler to fill the remaining space.
<div class="main">
<div class="a"><a href="#">Home</a></div>
<div class="b"><a href="#">Some title centered</a></div>
<div class="filler"></div>
<div class="c"><a href="#">Contact</a></div>
</div>
.filler{
flex-grow: 1;
}
I have updated the solution with 3 different versions. This because of the discussion of the validity of using an additional filler element. If you run the code snipped you see that all solutions do different things. For instance setting the filler class on item b will make this item fill the remaining space. This has the benefit that there is no 'dead' space that is not clickable.
<div class="mainfiller">
<div class="a"><a href="#">Home</a></div>
<div class="b"><a href="#">Some title centered</a></div>
<div class="filler"></div>
<div class="c"><a href="#">Contact</a></div>
</div>
<div class="mainfiller">
<div class="a"><a href="#">Home</a></div>
<div class="filler b"><a href="#">Some title centered</a></div>
<div class="c"><a href="#">Contact</a></div>
</div>
<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>
<style>
.main { display: flex; justify-content: space-between; }
.mainfiller{display: flex;}
.filler{flex-grow:1; text-align:center}
.a, .b, .c { background: yellow; border: 1px solid #999; }
</style>