Search code examples
htmlcssflexboxalignment

justify: space-between with right aligned last element


Is there a way to accomplish this (with flexbox, or other)?

evenly distributed text

  • evenly distributed text
  • but first and last element sticks to the sides

I'm assuming this would need the flex items to be shrinkwrapped, which (I think) isn't possible.


Solution

  • space-between will work- check out the example below:

    body {
      margin: 0;
    }
    * {
      box-sizing: border-box;
    }
    .wrapper {
      display: flex;
      justify-content: space-between;
    }
    .wrapper > * {
      border: 1px solid;
    }
    <div class="wrapper">
      <div>one</div>
      <div>two</div>
      <div>three</div>
      <div>four</div>
      <div>five</div>
    </div>

    Another way is using auto margins for the items at the end- but it has a different effect- see demo below:

    body {
      margin: 0;
    }
    * {
      box-sizing: border-box;
    }
    .wrapper {
      display: flex;
      justify-content: space-around;
    }
    .wrapper > * {
      border: 1px solid;
    }
    .wrapper div:first-child {
      margin-right: auto;
    }
    .wrapper div:last-child {
      margin-left: auto;
    }
    <div class="wrapper">
      <div>one</div>
      <div>two</div>
      <div>three</div>
      <div>four</div>
      <div>five</div>
    </div>