Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I align 2 first elements on the left and the last one on the right [duplicate]

I think my code is in order, but I do not know why I am unable to organize my elements in this way:

|**   *|

This is my code:

.container {
  border: 1px solid red;
  display: flex;
  justify-content: flex-start;
  width: 100%;
  height: 200px;
  flex-direction: row;
}

.container div {
  border: 1px solid blue;
  height: 100px;
  width: 100px;
}

.right {
  display: flex;
  align-self: flex-end;
}
<div class="container">
  <div>
    1
  </div>
  <div>
    2
  </div>
  <div class="right">
    3
  </div>
</div>

What am I doing wrong? This is my live code: https://jsfiddle.net/uxpkh9nL/

like image 967
yavg Avatar asked Mar 30 '19 04:03

yavg


People also ask

How do you align left and right items in 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.


1 Answers

Instead of align-self: flex-end (in row flex-direction, align-self and align-items align flex items in the cross axis which means vertically) - you can use margin-left: auto on the right element - see demo below:

.container{
  border:1px solid red;
  display:flex;
  justify-content:flex-start;
  width:100%;
  height: 200px;
  flex-direction:row;
}
.container div{
  border:1px solid blue;
  height: 100px;
  width: 100px;
}

.right{
  display:flex;
  /*align-self:flex-end;*/
  margin-left: auto; /* added */
}
<div class="container">
  <div>
    1
  </div>
  <div>
    2
  </div>  
  <div class="right">
    3
  </div>  
</div>

I prefer using margins in this case but you can also use a pseudo element and use to space out the items and using flex-grow: 1 on that.

  • adding order: 1 to the flex items, order: 2 to the pseudo element and order: 3 to the right elements places the flex items in that order.

  • adding flex-grow: 1 to the pseudo element forces it to fill all the remaining space left thereby placing the right element to the right end.

But this is an overkill if you ask me - see demo below:

.container{
  border:1px solid red;
  display:flex;
  justify-content:flex-start;
  width:100%;
  height: 200px;
  flex-direction:row;
}
.container div{
  border:1px solid blue;
  height: 100px;
  width: 100px;
  order: 1; /* added */
}

.right{
  display:flex;
  /*align-self:flex-end;*/
  order: 3 !important; /* added */
}

.container:after { /* added */
  order: 2;
  content: '';
  display: block;
  flex-grow: 1;
}
<div class="container">
  <div>
    1
  </div>
  <div>
    2
  </div>  
  <div class="right">
    3
  </div>  
</div>
like image 168
kukkuz Avatar answered Sep 23 '22 21:09

kukkuz