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.

3 Answers 3

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

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>

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.