如何通过链接和下拉菜单项将此导航栏居中?

时间:2018-11-27 16:52:41

标签: html css navbar

我试图弄清楚如何将包含链接和下拉项的导航栏居中。我能够使链接以它们自己为中心,而下拉菜单项也以它们自己为中心,但是当尝试使它们全部居中时,它们将显示为水平居中而不是垂直居中。目前,它们看起来像这样left aligned。当我将浮点数更改为无(并按建议添加flex)时,我得到了这个improperly centered

.navbar {
  overflow: hidden;
}

.navbar a {
  float: left;
  padding: 14px 16px;
  background-color: #666666;
}

.dropdown {
  float: left;
  overflow: hidden;
}

.dropdown .dropbtn {
  padding: 14px 16px;
  margin: 0;
}

.dropdown-content {
  display: none;
  position: absolute;
  min-width: 160px;
  z-index: 1;
}

.dropdown-content a {
  float: none;
  padding: 12px 16px;
  display: block;
  text-align: left;
}

.dropdown:hover .dropdown-content {
  display: block;
}
<div class="navbar">
  <a href="#">a</a>
  <div class="dropdown">
    <button class="dropbtn">b</button>
    <div class="dropdown-content">
      <a href="#">1</a>
      <a href="#">2</a>
    </div>
  </div>
  <div class="dropdown">
    <button class="dropbtn">c</button>
    <div class="dropdown-content">
      <a href="#">3</a>
      <a href="#">4</a>
    </div>
  </div>
  <a href="#">d</a>
</div>

1 个答案:

答案 0 :(得分:0)

您可以在其中使用flex ...

.navbar {
  overflow: hidden;
  display: flex;
  justify-content:center;
}

.navbar a {
  float: left;
  padding: 14px 16px;
  background-color: #666666;
}

.dropdown {
  float: left;
  overflow: hidden;
}

.dropdown .dropbtn {
  padding: 14px 16px;
  margin: 0;
}

.dropdown-content {
  display: none;
  position: absolute;
  min-width: 160px;
  z-index: 1;
}

.dropdown-content a {
  float: none;
  padding: 12px 16px;
  display: block;
  text-align: left;
}

.dropdown:hover .dropdown-content {
  display: block;
}
<div class="navbar">
  <a href="#">a</a>
  <div class="dropdown">
    <button class="dropbtn">b</button>
    <div class="dropdown-content">
      <a href="#">1</a>
      <a href="#">2</a>
    </div>
  </div>
  <div class="dropdown">
    <button class="dropbtn">c</button>
    <div class="dropdown-content">
      <a href="#">3</a>
      <a href="#">4</a>
    </div>
  </div>
  <a href="#">d</a>
</div>