3

.parent {
  display: flex;
  justify-content: flex-end;
  background-color: lightgray;
}

.child {
  width: 200px;
  height: 200px;
  background-color: gray;
  border: solid black 1px;
}

.center {
  margin: 0 auto;
  background-color: black
}
<div class="parent">
  <div class="child center"> </div>
  <div class="child"> </div>
  <div class="child"> </div>
</div>

and this is what i've got.

It seems the black one is located in the a little left, not the "center" of the parent. How can i fix this?

YO Y
  • 111
  • 7
  • Would you want the three elements to still stack in smaller screens where there is limited space? – Yong Feb 09 '22 at 03:57

1 Answers1

3

If you don't mind using grid instead of flexbox, you can utilize the property justify-self to align the black box to the center with the help of position: absolute;. The absolute positioning here makes it so it's possible to align the black box toward the center without minding/affecting the other two boxes. See the snippet below:

.parent {
  display: grid;
  justify-content: flex-end;
  grid-auto-flow: column;
  background-color: lightgray;
  position: relative;
}

.child {
  width: 200px;
  height: 200px;
  background-color: gray;
  border: solid black 1px;
}

.center {
  background-color: black;
  justify-self: center;
  position: absolute;
}

@media screen and (max-width: 992px) {
  .parent{
    display: flex;
    flex-wrap: wrap;
  }
  .center {
    position: relative;
  }
}
<div class="parent">
  <div class="child center"> </div>
  <div class="child"> </div>
  <div class="child"> </div>
</div>

PS. I've added a @media query in case you want the 3 boxes to stack on a smaller space/screen.

Edit: Changed display on smaller screens and applied wrapping when necessary using flex-wrap.

More on justify-self and grid here and here respectively.

Yong
  • 1,622
  • 1
  • 4
  • 29
  • Thank you, it works! Could i also wrap the black one and the gray ones when the screen shrinks? like ```flex-wrap: wrap``` on the parent – YO Y Feb 09 '22 at 08:10
  • 1
    @YOY edited the snippet to enable wrapping. You can check the changes above. – Yong Feb 09 '22 at 08:49
  • 1
    That's what i exactly wanted. you added ```display:flex; flex:wrap:wrap;``` in ```@media``` query. Thank you for sharing again! – YO Y Feb 09 '22 at 08:54