Search code examples
cssreactjsmaterialize

Reactjs materialize - how to center content in navbar


I'm trying to make a navbar using the materialize framework in my react project, and would like to have the first set of links sitting in the center of the navbar, and the second set on the right side of the navbar. I'm not sure how to do this - the helper classes "left" and "right" are working, however when I try to "center" my links, it defaults to the left side of the navbar. Here is the code I'm working with...

 <div className="App">
    <nav>
      <div class="nav-wrapper purple lighten-3">
        //I would like these links in the center
        <ul class="center">
          <li>
            <a href="sass.html">People</a>
          </li>
          <li>
            <a href="badges.html">Places</a>
          </li>
        </ul>
        //I would like these links on the right
        <ul class="right">
          <li>
            <a href="sass.html">Sass</a>
          </li>
          <li>
            <a href="badges.html">Components</a>
          </li>
        </ul>
      </div>
    </nav>
  </div>

I've also added some css recommended on a similar post:

.nav-wrapper.center {
  display: flex;
  justify-content: center;
}

Here's my sandbox:

https://codesandbox.io/s/tender-buck-ktzxe?file=/src/App.js

Wondering if anyone can help me.

Thanks!


Solution

  • You could use absolute positioning, the same way Materialize uses it for centering the .brand-logo

    ul.center {
      position: absolute;
      left:50%;
      transform: translate(-50%);
    }
    

    Codepen here.

    Here are the styles Materialize uses to center the .brand-logo:

    nav .brand-logo.center {
        left: 50%;
        -webkit-transform: translateX(-50%);
        transform: translateX(-50%);
    }
    
    nav .brand-logo {
        position: absolute;
        color: #fff;
        display: inline-block;
        font-size: 2.1rem;
        padding: 0;
    }