24

In the old days I would have used two containers and floated one left and the other right using clearfix. But I think that method is a bit antiquated with flex capabilities being well supported now.

Problem is I have no idea how to lay this out using flex.

Here is a screenshot with some buttons. Secondary action is aligned left and the other two primary actions should be right aligned.

enter image description here

Here is the markup I have:

<footer>
    <button>Back</button>
    <span class="primary-btns">
        <button>Cancel</button>
        <button>Go</button>
    </span>
</footer>

Can someone tell me what CSS flex methods I should use here?

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
chovy
  • 72,281
  • 52
  • 227
  • 295

2 Answers2

33

You can just use justify-content: space-between

footer {
  display: flex;
  justify-content: space-between;
}
<footer>
  <button>Back</button>
  <span class="primary-btns">
    <button>Cancel</button>
    <button>Go</button>
  </span>
</footer>

Update: You can also do this without span with margin-left: auto DEMO

Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
15

You don't even need a nested container in this case.

Modern CSS technologies (flex and grid) make this layout simple and require just one container.

footer {
  display: flex;
}

button:first-child {
  margin-right: auto;
}

button {
  margin: 5px;
}
<footer>
  <button>Back</button>
  <button>Cancel</button>
  <button>Go</button>
</footer>

Flex auto margins consume all free space in the specified direction.

This would also work:

button:nth-child(2) { margin-left: auto }

All about auto margins here: Methods for Aligning Flex Items

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701