Correctly center Navitems

Viewed 28

So at the moment my Nav Items are centered by Margin, but this only works correctly when the Items are of same size, which they are not. How can i center it correctly?

<Navbar bg={ transparent ? "" : "dark"} variant="dark" expand="md" fixed="top">
  <Container fluid>
    <Navbar.Brand href="/">Logo</Navbar.Brand>
    <Navbar.Toggle aria-controls="basic-navbar-nav" />
    <Navbar.Collapse id="basic-navbar-nav">
      <Nav className="ms-auto d-flex w-100 align-items-center justify-content-center">
        <Nav.Item className="ms-md-auto">
          <Nav.Link className={textColor} href="/about">
            About
          </Nav.Link>
        </Nav.Item>
        <Nav.Item>
          <Nav.Link className={textColor} href="/blog">
            Blog
          </Nav.Link>
        </Nav.Item>
        <Nav.Item>
          <Nav.Link className={textColor} href="/writeups">
            Writeups
          </Nav.Link>
        </Nav.Item>
        { 
        (Object.getOwnPropertyNames(userProfile).length === 0) &&

          <Nav.Item className="ms-md-auto">
            <Nav.Link className={textColor} href="/sign-up">
              Sign Up
            </Nav.Link>
          </Nav.Item>
        }
        { 
        (Object.getOwnPropertyNames(userProfile).length === 0) &&

        <Nav.Item>
          <Nav.Link className={textColor} href="/sign-in">
            Sign In
          </Nav.Link>
        </Nav.Item>
        }
        {
          (Object.getOwnPropertyNames(userProfile).length !== 0) &&

          <Nav.Item className='ms-md-auto text-align-center' id='123'>
            <Nav.Link 
              className={textColor.concat(" btn")} 
              href={"/profile/" + String(userProfile.id)}
            >
              <img 
                style={{height: '35px', borderRadius: '30px'}}
                src={'http://localhost:8000' + userProfile.avatar}
              />&nbsp;&nbsp;&nbsp;{userProfile.username}
            </Nav.Link>
          </Nav.Item>
        }

      </Nav>
    </Navbar.Collapse>
  </Container>
</Navbar>

The Logo and Heading below the Navbar are centered, but the middle nav items arent.

enter image description here

1 Answers

Here is a JSFiddle that shows a possible solution:

https://jsfiddle.net/r76goewz/

This uses the following syntax (it uses d-flex classes but I believe it should work without it on nav elements because they are already defined as flex elements:

<div class="d-flex">
  <div class="d-flex flex-1 justify-content-start">Flex item foobar foobar foobar</div>
  <div class="d-flex">centered</div>
  <div class="d-flex flex-1 justify-content-end">Flex item</div>
</div>

Example:

enter image description here

All that is need is to add an extra css class to simplify the code a little bit (there is no shorthand for this in Bootstrap 5 afaik):

.flex-1 {
    /* Shorthand for flex-grow: 1, flex-shrink: 1, flex-basis: 0 */
    flex: 1;
}
Related