Search code examples
htmlcsscss-grid

vertically align right aligned navbar items within grid


I want to create a navbar using the CSS grid attribute. Currently I have this

#navbar {
  height: 60px;
  display: grid;
  justify-items: right;
  padding: 20px;
  background: red;
}

#navbarLinkContainer {}

a {
  text-decoration: none;
  margin: 0 10px;
  color: white;
  background: black;
}
<div id="navbar">
  <div id="navbarLinkContainer">
    <a href="/">Home</a>
    <a href="/about">About</a>
    <a href="/projects">Projects</a>
    <a href="/contact">Contact</a>
    <a href="/imprint">Imprint</a>
  </div>
</div>

and my problem is that I don't know how to center the links vertically within the navbarLinkContainer.

I tried to add align-items: center and vertical-align: middle to the navbarLinkContainer but this didn't help. So how can I center the links within the navbar?


Solution

  • Why not use align-items: center on the #navbar instead; since it is a flex-container it will align its children at the middle; also changed your justify-items: right to justify-content: end

    #navbar {
      height: 60px;
      display: grid;
      justify-content: end;
      padding: 20px;
      background: red;
      align-items: center;
    }
    
    #navbarLinkContainer {}
    
    a {
      text-decoration: none;
      margin: 0 10px;
      color: white;
      background: black;
    }
    <div id="navbar">
      <div id="navbarLinkContainer">
        <a href="/">Home</a>
        <a href="/about">About</a>
        <a href="/projects">Projects</a>
        <a href="/contact">Contact</a>
        <a href="/imprint">Imprint</a>
      </div>
    </div>