-1

Using a flexbox container, how can I have the first child centered and the second child at the end? I tried the following but it didn't work:

.flexbox {
  display: flex;
  justify-content: center;
  height: 200px;
}

.box1 {
  width: 100px;
}

.box2 {
  width: 100px;
  justify-self: end; /* does nothing */
}

div{ border: 1px solid black; } /* to help see the divs */
<div class="flexbox">
  <div class="box1"></div>
  <div class="box2"></div>
</div>
AskYous
  • 4,332
  • 9
  • 46
  • 82

4 Answers4

1

Justify-self only works with grid not flexbox

.flexbox {
  display: grid;
  grid-template-columns: auto auto;
  height: 200px;
  width: 500px;
  background: orange;
}

.box1 {
  width: 100px;
  height: 200px; 
  background: red;
  justify-self: end;
}

.box2 {
  width: 100px;
  justify-self: end;
  height: 200px; 
  background: blue;
}
<div class="flexbox">
  <div class="box1"></div>
  <div class="box2"></div>
</div>

For your problem though, you can solve it using absolute positioning

.flexbox {
  position: relative;
  display: flex;
  justify-content: center;
  height: 200px;
  width: 500px;
  background: orange;
}

.box1 {
  width: 100px;
  height: 200px;
  background: red;
}

.box2 {
  position: absolute;
  width: 100px;
  height: 200px;
  background: blue;
  top: 0;
  right: 0;
}
<div class="flexbox">
  <div class="box1"></div>
  <div class="box2"></div>
</div>
0

You could make a first box that's invisible and then using flex: space-between. Here's how I did it.

.flexbox {
  display: flex;
  justify-content: space-between;
  height: 200px;
}

.flexbox-again {
  display: flex;
  justify-content: flex-end;
  height: 200px;
}

.box0 {
  width: 100px;
  background: none;
}

.box1 {
  width: 100px;
  background: blue;
}

.box2 {
  background: red;
  width: 100px;
  justify-self: end; // does nothing
}
<div class="flexbox">
  <div class="box0"></div>
  <div class="box1"></div>
  <div class="box2"></div>
</div>
feetnappy
  • 513
  • 1
  • 4
  • 10
ben
  • 55
  • 2
  • 9
0

Use align-self property. It will work

.box2 {
     width: 100px;
     align-self: flex-end;
}
devzakir
  • 387
  • 3
  • 15
  • I tested this and it didn't work... though I'm sure that `align-self` is for the axis perpendicular to the flex-direction so I didn't expect it to work. – AskYous Mar 30 '18 at 22:15
-1

You can do center the first element using margin-left: 50%; and right align the second element using margin-right: 0; Remove justify-contect: center from your main div.

.flexbox { 
    display: flex; 
    height: 200px;
    background: yellow;
}
.box1 { 
  width: 100px; 
  margin-left: 50%;
  background: blue;
}
.box2 { 
    width: 100px; 
    margin-left: auto;
    margin-right: 0;
    background: green;
}
<div class="flexbox">
    <div class="box1">fdgdfg</div>
    <div class="box2">dfgdg</div>
</div>
Kavindra
  • 1,697
  • 2
  • 14
  • 19