1

I'm trying to create a layout where most of my items align to the left of the viewport, but one item needs to align to the right.

I would rather not use float: right; in this instance and would prefer to make use of justify-content: flex-end;

I have made a codepen which visually shows the correct layout, but it has an extra div (I've titled it .remove-this-div) that I'd rather not have there, as I want to keep my mark-up as clean as possible and avoid wrapper divs where they are not required

Codepen

The mark-up I'm after whilst still getting the button to align right is like this:

<section>
  <div>I sit to the left</div>
  <div>I sit to the left</div>
  <div>I sit to the left</div>
  <div>I sit to the left</div>
  <button>I sit to the right</button>
</section>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
user1486133
  • 1,309
  • 3
  • 19
  • 37

2 Answers2

2

section {
  display: flex;
  flex-direction: column;
  width: 500px;
}

button { 
  align-self: flex-end;   /* `margin-left: auto` would also work */
} 

section > * {
  outline: 1px solid black;
}
<section>
  <div>I sit to the left</div>
  <div>I sit to the left</div>
  <div>I sit to the left</div>
  <div>I sit to the left</div>
  <button>I sit to the right</button>
</section>

Revised Codepen

More about flex alignment and auto margins here: Methods for Aligning Flex Items

Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
0

The property you're looking for here is align-self:

section{
    display:flex;
    font-family:sans-serif;
    flex-direction:column;
    justify-content:flex-start;
}
button{
    align-self:flex-end;
}
<section>
    <div>I sit to the left</div>
    <div>I sit to the left</div>
    <div>I sit to the left</div>
    <div>I sit to the left</div>
    <button>I sit to the right</button>
</section>
Shaggy
  • 6,696
  • 2
  • 25
  • 45