在网格内垂直对齐右对齐的导航栏项目

时间:2019-04-15 18:19:51

标签: html css css-grid

我想使用CSS grid属性创建一个导航栏。目前我有这个

#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>

我的问题是我不知道如何在navbarLinkContainer内将链接垂直居中。

我尝试将align-items: centervertical-align: middle添加到navbarLinkContainer上,但这没有帮助。那么如何在导航栏中将链接居中?

3 个答案:

答案 0 :(得分:1)

为什么不在align-items: center上使用#navbar;由于它是一个柔性容器,因此它将其子对象对准中间;也将您的justify-items: right更改为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>

答案 1 :(得分:1)

您只需将align-items: center添加到您的#navbar

#navbar {
  height: 60px;
  display: grid;
  justify-items: right;
  align-items: center;
  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>

答案 2 :(得分:-2)

如果您希望所有链接都位于中心,则可以修改“ justify-items:center;”。在导航栏中

#navbar {
  height: 60px;
  display: grid;
  justify-items: center;
  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>