how to align items in the center and right

Viewed 74

.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?

1 Answers

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.

Related