Shamseer Ahammed
Shamseer Ahammed

Reputation: 1947

Aligning flex items to the right

I have a container and inside there are 3 boxes: yellow, green and red.

I gave display:flex to the container and gave justify-content:flex-start for the items to start at beginning.

I wanted to move the red box to the end so I gave margin-right: auto to the yellow box so that the red box could move to end (not sure if this is the exact way to move the red box to end, if not i want help in that too).

So the question is: I want the green box in the vertical middle of the container and I want to move it to the extreme right like the red box (but should be in the middle of container)

How do I do it with flex box?

.container {
  height: 500px;
  width: 500px;
  background-color: royalblue;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
}
.yellowbox {
  color: black;
  height: 100px;
  width: 100px;
  background-color: yellow;
  margin-right: auto;
}
.greenbox {
  color: black;
  height: 100px;
  width: 100px;
  background-color: green;
  align-self: center;
  margin-left: auto;
}
.redbox {
  color: black;
  height: 100px;
  width: 100px;
  background-color: red;
}
<div class="container">
  <div class="yellowbox">
    <p>the white text</p>
  </div>
  <div class="greenbox">
    <p>the black text</p>
  </div>
  <div class="redbox">
    <p>the red text</p>
  </div>
</div>

THIS IS MY CODEPEN LINK: http://codepen.io/ShamZ/pen/pRLELP

Upvotes: 2

Views: 112

Answers (1)

G-Cyrillus
G-Cyrillus

Reputation: 106048

you may increase some of the margins but you must allow the flex children to wrap. and use order to put the green box in last position

.container {
  height: 500px;
  width: 500px;
  background-image:linear-gradient(to left,rgba(0,0,0,0.2) 50%,rgba(0,0,0,0.1) 50%),linear-gradient(to top,rgba(0,0,0,0.2) 50%,rgba(0,0,0,0.1) 50%);
  background-color: royalblue;
  display: flex;
  flex-direction: row;
  flex-wrap:wrap;
  justify-content:space-between;
}
.yellowbox {
  color: black;
  height: 100px;
  width: 100px;
  background-color: yellow;
  margin-right: 50%;
}
.greenbox {
  order:1;
  color: black;
  height: 100px;
  width: 100px;
  background-color: green;
  margin: -100px 0 auto auto;
}
.redbox {
  margin:0 0 0 auto;
  color: black;
  height: 100px;
  width: 100px;
  background-color: red;
}
<div class="container">
  <div class="yellowbox">
    <p>the white text</p>
  </div>
  <div class="greenbox">
    <p>the black text</p>
  </div>
  <div class="redbox">
    <p>the red text</p>
  </div>
</div>

http://codepen.io/gc-nomade/pen/Qdmpbb

Upvotes: 1

Related Questions