3

How can I use flexbox to align .right to the very end of div?

My CSS:

div {
  display: flex;
  border: 1px dotted black;
}
.right {

}

HTML:

<div>
  <span>Left</span>
  <span class="right">Right</span>
</div>

Codepen Link

Thanks.

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Karolina Ticha
  • 531
  • 4
  • 19

3 Answers3

3

Three ways:

  1. Use justify-content: space-between on the container.

    div {
        display: flex;
        border: 1px dotted black;
        justify-content: space-between; /* new */
    }
    

    Revised Codepen


  1. Use auto margins on the first flex item.

    div > span:first-child { margin-right: auto; }
    

    Revised Codepen


  1. Use auto margins on the second flex item.

    .right { margin-left: auto; }
    

    Revised Codepen


For an explanation of justify-content and auto margins, along with examples and illustrations, see this post: Methods for Aligning Flex Items along the Main Axis

Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
2

As per section 8.1 in the CSS Flexible Box Layout Module, you can use auto margins in order to position the element.

In this case, you could add margin-left: auto in order to position the element to the right. In doing so, any positive free space is distributed to that side of the element which effectively positions it to the very right like in the example below.

div {
  display: flex;
  border: 1px dotted black;
}
.right {
  margin-left: auto;
}
<div>
  <span>Left</span>
  <span class="right">Right</span>
</div>
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
0

Use margin-left: auto; margin-right: 0; so that the element is pushed to the right! Also you have a typo here:

<span class="righ">Right</span>
<!---------------^ t missing.

See the working snippet:

div {
  display: flex;
  border: 1px dotted black;
}
.right {
  margin-left: auto;
  margin-right: 0;
}
<div>
  <span>Left</span>
  <span class="right">Right</span>
</div>
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252