将弹性项目放在列表中居中

问题描述 投票:0回答:2

所以我在从正在制作的菜单中对项目进行居中时遇到问题。

我尝试放入justify-content: center,但这似乎不起作用。有人可以帮忙吗?

现在菜单被卡在左上角。我想居中。

.header2 {
  background-color: rgb(190, 13, 13);
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  padding: 15px;
}

.menu {
  display: flex;
}

.menu li {
  margin-right: 15px;
}

.menu li a {
  display: block;
  padding: 10px;
}
<nav class="header2">
  <ul class="menu">
    <li><a href="#">Home</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Products</a></li>
    <li><a href="#">Contacts</a></li>
  </ul>
</nav>
css flexbox centering
2个回答
2
投票

嵌套的flexbox(.menu)默认情况下设置为flex-grow: 0,这意味着它不会占据父级的整个长度。

因此,应用justify-content: center无效,因为容器中没有可用空间。

enter image description here

添加flex-grow: 1可提供您所需的额外空间:

enter image description here

将此添加到您的代码中:

.menu {
    display: flex;
    flex: 1;
    justify-content: center;
}

此外,由于您已经在使用语义上有意义的nav元素,因此实际上不需要嵌套列表元素。请尝试使用以下简化代码:

.menu {
  display: flex;
  justify-content: center;
  background-color: rgb(190, 13, 13);
}

.menu a {
  padding: 25px 10px;
}

.menu a:hover {
  background-color: orangered;
}
<nav class="menu">
  <a href="#">Home</a>
  <a href="#">About</a>
  <a href="#">Products</a>
  <a href="#">Contacts</a>
</nav>

1
投票

尝试:

.menu {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    flex-grow: 1; /* or width: 100% */
}

如果您希望元素在所有宽度上均匀分布。

和:

.menu {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    flex-grow: 1; /* or width: 100% */
}

否则。

© www.soinside.com 2019 - 2024. All rights reserved.