创建导航栏,项目使用完整 space (css)

creating a navbar, items using full space (css)

我不是使用 css 的专家,在这个问题上花费 1 小时后我会问社区。

我的html代码:

 <div class="content2">
    <div class="Menu">
        <a href="/all">All Investments (3)</a>
        <a href="/payouts">Payouts (0)</a>
    </div>
    ...some other code
 </div>

我的css代码:

.content2 {padding: 10px 30px; color: #fff}
.Menu {background: #022000; width: 1000px; height: 50px; margin: 20px auto; text-align: center}
.Menu a {float: left; height: 26px; width: 313px; padding: 12px 10px; color: #fff}
.Menu a:hover {background: #277521}

我希望我的菜单中的两个项目 class 完全填满导航栏的宽度。目前他们不占用导航栏的完整宽度。

使用width: 50%;并将填充修改为padding: 12px 0px;

解释:

  • width: 50% :因为有 2 个元素,这将使每个元素占据父元素宽度的 50%。

  • padding: 12px 0px :左右填充 0px 有助于删除每个元素所需的额外 space。

.content2 {
  padding: 10px 30px;
  color: #fff
}
.Menu {
  background: #022000;
  width: 1000px;
  height: 50px;
  margin: 20px auto;
  text-align: center
}
.Menu a {
  float: left;
  height: 26px;
  width: 50%;
  padding: 12px 0px;
  color: #fff;
    background-color: yellow;
}
.Menu a:hover {
  background: #277521
}
<div class="content2">
  <div class="Menu">
    <a href="/all">All Investments (3)</a>
    <a href="/payouts">Payouts (0)</a>
  </div>
  ...some other code
</div>

用 flex 试试。添加这些样式:

.Menu {display: flex;}
.Menu a {flex: 1;}

这将适用于任意数量的菜单项,而不仅仅是 2 个。

提示:flex 非常强大属性,如果您对我的代码为何有效感兴趣,我建议您稍微研究一下。

试试下面的方法。

width:50%box-sizing: border-box; 交给 a。并更改 height:50px;

.content2 {
  padding: 10px 30px;
  color: #fff
}
.Menu {
  background: #022000;
  width: 1000px;
  height: 50px;
  margin: 20px auto;
  text-align: center
}
.Menu a {
  float: left;
  height: 50px;
  width: 50%;
  padding: 12px 10px;
  color: #fff;
  box-sizing: border-box;
}
.Menu a:hover {
  background: #277521
}
<div class="content2">
  <div class="Menu">
    <a href="/all">All Investments (3)</a>
    <a href="/payouts">Payouts (0)</a>
  </div>
  ...some other code
</div>

Working Fiddle

.content2 {
  padding: 10px 30px;
  color: #fff
}
.Menu {
  background: #022000;
  width: 1000px;
  height: 50px;
  margin: 20px auto;
  text-align: center
}
.Menu a {
  float: left;
  height: 26px;
  width: 50%;
  padding: 12px 0px;
  color: #fff;
    background-color: yellow;
}
.Menu a:hover {
  background: #277521
}
<div class="content2">
  <div class="Menu">
    <a href="/all">All Investments (3)</a>
    <a href="/payouts">Payouts (0)</a>
  </div>
  ...some other code
</div>