3

I am trying using flexbox to horizontally center a menu but have its last element on the right side of the website.

Here is a schema:

schema

I have tried setting the margin-left to auto on the last element but it sends the centered menu to the left. Setting margin-right to auto for the menu doesn't work.

I have a "hack"-solution: placing an invisible copy (visibility hidden) of the last element before the centered part of the menu and setting its margin-right to auto.

Any better hack-free solution?

Here is a code sample:

#container {
  display: flex;
  justify-content: center;
  align-items: center;
}
#last {
  margin-left: auto;
}
<div id="container">
  <div id="menu">
    <span>1</span>
    <span>2</span>
    <span>3</span>
  </div>
  <div id="last">
    4
  </div>
</div>

Thanks!

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701

1 Answers1

3

Give also #menu a left margin of auto.

Stack snippet

#container {
  display: flex;
  justify-content: center;
  align-items: center;
}
#last, #menu {
  margin-left: auto;
}

#last span, #menu span {
  padding: 10px 20px;
  background: lightgray;
}
<div id="container">
  <div id="menu">
    <span>1</span>
    <span>2</span>
    <span>3</span>
  </div>
  <div id="last">
    <span>4</span>
  </div>
</div>

If you want the #menu in the exact middle of its parent, we can achieve that by adding a pseudo to match the #last.

The flex: 1 will then take all the available space, and push the #menu to the middle

Stack snippet

#container {
  display: flex;
  justify-content: center;
  align-items: center;
}

#last, #container::before {
  content: '';                /*  for the pseudo to render  */
  flex: 1;                    /*  take all space left, equally  */
  text-align: right;
}

#last span, #menu span {
  padding: 10px 20px;
  background: lightgray;
}
<div id="container">
  <div id="menu">
    <span>1</span>
    <span>2</span>
    <span>3</span>
  </div>
  <div id="last">
    <span>4</span>
  </div>
</div>
Asons
  • 84,923
  • 12
  • 110
  • 165