Karolina Ticha
Karolina Ticha

Reputation: 531

Flexbox alignment to end of div

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.

Upvotes: 3

Views: 326

Answers (3)

Michael Benjamin
Michael Benjamin

Reputation: 371193

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

Upvotes: 3

Josh Crozier
Josh Crozier

Reputation: 240908

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>

Upvotes: 2

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

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>

Upvotes: 0

Related Questions