将弹性项目放在列表中 [英] Centering flex items inside a list

查看:56
本文介绍了将弹性项目放在列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I'm having a problem centering items from a menu I'm making.

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

I have tried to put justify-content: center but that does not seem to work. Can someone help?

现在,菜单停留在左上角.我想居中.

Right now the menu is stuck on the left corner. I want to center it.

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

推荐答案

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

The nested flexbox (.menu) is set, by default, to flex-grow: 0, which means it won't occupy the full length of the parent.

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

Therefore, applying justify-content: center has no effect because there's no free space available in the container.

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

Adding flex-grow: 1 provides the extra space you need:

将此添加到您的代码中:

Add this to your code:

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

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

Also, since you're already using the semantically meaningful nav element, there's really no need for a nested list element. Try this simplified code instead:

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

这篇关于将弹性项目放在列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆