-1

I currently have 3 items. I would like the 1st item left-aligned and the last 2 right-aligned next to each other. I can't seem to be able to make the middle box go to the right. The justify self attributes were a bit confusing and so I posted my question here. Here is my code.

.box {
  display: flex;
}

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

.box2 {
  width: 100px;
  height: 100px;
  margin-left: auto;
}

.box3 {
  width: 100px;
  height: 100px;
  margin-left: auto;
}
<div class="box">
  <div class="box1"></div>
  <div class="box2"></div>
  <div class="box3"></div>
</div>
Jacklyn N
  • 77
  • 1
  • 12

2 Answers2

3

You don't need an auto margin on the last item.

.box {
  display: flex;
}

.box2 {
  margin-left: auto;
}

.box3 {
  /* margin-left: auto; */
}

.box > div {
  flex: 0 0 100px;
  height: 100px;
  border: 1px solid black;
}
<div class="box">
  <div class="box1"></div>
  <div class="box2"></div>
  <div class="box3"></div>
</div>

Auto margins consume all available space in the specified direction.

When you apply margin-left: auto to two items, they divide the free space equally between them. As a result, there are gaps.

Just apply the margin to the second item, so it consumes all free space, pinning both itself and its sibling to the right.

More info here: Methods for Aligning Flex Items along the Main Axis

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

.box {
  display: flex;
}

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

}
.box2 {
  width: 100px;
  height: 100px;
margin-left:auto;
background-color:blue;
}
.box3 {
  width: 100px;
  height: 100px;
margin-right: 0;
background-color:yellow;
}
<div class="box">
  <div class ="box1">box1</div>
<div class ="box2">box2</div>
<div class ="box3">box3</div>
</div>
ikiK
  • 6,328
  • 4
  • 20
  • 40