Search code examples
htmlcssflexboxalignment

Evenly space children but right-align parent with flex


I have the following code to setup a menu. The idea is to have the menu items evenly spaced horizontally, but not have them spaced too far apart when there is extra space. If there is extra space, right now the menu aligns to the left (the green is towards the left side of the yellow).

The aim is to have the menu align to the right side. How can this be achieved?

.wrapper {
  display: flex;
  height: 5em;
}
.left {
  flex: 1;
  display: flex;
}
.middle {
  flex: 4;
  background: #ffc;
  display: flex!important; /* this comes from the library i'm using */
}
ul {
  display: flex;
  max-width: 200px;
}
li {
  list-style: none;
  flex: 1;
  background: #cfc;
  text-align: center;
}
.right {
  flex: 1;
}
<div class="wrapper">
  <div class="left">
    <div class="tagline">Left</div>
  </div>
  <div class="middle">
    <ul>
      <li>menu item</li>
      <li>menu item</li>
      <li>menu item</li>
      <li>menu item</li>
    </ul>
  </div>
  <div class="right">
    right
  </div>
</div>


Solution

  • To align the menu items to the right, we can have margin-left: auto on the ul. And maybe you want to set the default padding of ul to zero too.

    See demo below:

    .wrapper {
      display: flex;
      height: 5em;
    }
    .left {
      flex: 1;
      display: flex;
    }
    .middle {
      flex: 4;
      background: #ffc;
      display: flex!important; /* this comes from the library i'm using */
    }
    ul {
      display: flex;
      max-width: 200px;
      margin-left: auto; /* ADDED */
      padding: 0; /* ADDED */
    }
    li {
      list-style: none;
      flex: 1;
      background: #cfc;
      text-align: center;
    }
    .right {
      flex: 1;
    }
    <div class="wrapper">
      <div class="left">
        <div class="tagline">Left</div>
      </div>
      <div class="middle">
        <ul>
          <li>menu item</li>
          <li>menu item</li>
          <li>menu item</li>
          <li>menu item</li>
        </ul>
      </div>
      <div class="right">
        right
      </div>
    </div>