Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using flexbox, left-align and right-align elements in one row

Tags:

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?

like image 970
chovy Avatar asked May 10 '16 18:05

chovy


People also ask

How do you align left and right on flex?

The flex columns can be aligned left or right by using the align-content property in the flex container class. The align-content property changes the behavior of the flex-wrap property. It aligns flex lines. It is used to specify the alignment between the lines inside a flexible container.

How can I align one item right with flexbox?

To align one flex child to the right set it with margin-left: auto; From the flex spec: One use of auto margins in the main axis is to separate flex items into distinct "groups".


2 Answers

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

like image 108
Nenad Vracar Avatar answered Sep 29 '22 12:09

Nenad Vracar


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

like image 36
Michael Benjamin Avatar answered Sep 29 '22 14:09

Michael Benjamin