10

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/

kukkuz
  • 41,512
  • 6
  • 59
  • 95
yavg
  • 2,761
  • 7
  • 45
  • 115

1 Answers1

6

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>
kukkuz
  • 41,512
  • 6
  • 59
  • 95
  • it works, but ... is there any way to achieve it with flexbox? – yavg Mar 30 '19 at 04:20
  • you don't have any `justify-self` in *flexbox* - alignment in *flex axis* with margins *is* the flexbox way :) will add another option to the answer... – kukkuz Mar 30 '19 at 04:22
  • 1
    I'm just learning flexbox, it's something complex for me what you did, you can detail it please, since you're the best answer. – yavg Mar 30 '19 at 04:34