Skip to content Skip to sidebar Skip to footer

Flexbox Horizontal Menu Centering While Keeping Last Element To The Right Side

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: I have tried setting the margin-left to auto

Solution 1:

Give also #menu a left margin of auto.

Stack snippet

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

#lastspan, #menuspan {
  padding: 10px20px;
  background: lightgray;
}
<divid="container"><divid="menu"><span>1</span><span>2</span><span>3</span></div><divid="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;
}

#lastspan, #menuspan {
  padding: 10px20px;
  background: lightgray;
}
<divid="container"><divid="menu"><span>1</span><span>2</span><span>3</span></div><divid="last"><span>4</span></div></div>

Post a Comment for "Flexbox Horizontal Menu Centering While Keeping Last Element To The Right Side"