Warm tip: This article is reproduced from serverfault.com, please click

html-下拉导航菜单显示在右侧并水平堆叠

(html - Dropdown Nav Menu Appears on Right and Stacked Horizontally)

发布于 2020-11-28 02:23:14

我正在尝试为导航栏中的一项创建下拉菜单。我基于此W3Schools示例创建代码鼠标悬停时,菜单将显示在导航栏下方(应显示的状态),但它是1)水平堆叠而不是垂直堆叠,并且2)出现在页面的最右侧。我在这里查看过类似的问题,但无法在我的代码中找出问题。任何帮助,将不胜感激。

更新截图

/* nav */

nav {
  display: flex;
  flex-wrap: wrap;
  padding: .25rem 0;
  color: #ffffff;
  font: 30px 'Roboto', sans-serif;
  margin: auto;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  overflow: hidden;
}

nav a {
  display: block;
  margin: 0 40px;
}


/* dropdown container */

.dropdown {
  float: none;
  position: relative;
  overflow: visibile;
}


/* dropdown button */

.dropdown .dropbtn {
  display: flex;
  font-size: 30px;
  border: none;
  outline: none;
  color: #ffffff;
  padding: inherit;
  background-color: inherit;
  font-family: inherit;
  margin: auto;
}


/* dropdown content (hidden by default */

.dropdown-content {
  display: none;
  position: absolute;
  margin-top: 10px;
  background-color: #ffffff;
  width: 250px;
  left: calc(50% - 125px);
}

.dropdown-content>a {
  color: black;
  text-align: left;
  border-bottom: 1px solid #009EDB;
}


/* show dropdown menu on hover */

.dropdown:hover .dropdown-content {
  display: block;
  float: left;
  margin: 0;
}
<nav class="justify-content-center">

  <a href="/Users/Samantha/Desktop/Website/about.html" alt="About">About</a>

  <section class="dropdown">
    <button class="dropbtn">
                        Work
                    </button>
    <section class="dropdown-content">
      <a href="/Users/Samantha/Desktop/Website/Articles/articles.html" alt="Articles" target="_blank">Articles and Presentations</a>
      <a href="/Users/Samantha/Desktop/Website/Articles/Series/New Case Flow/from-process-to-flow-series.html" alt="From Process to Flow Series" target="_blank">From Process to Flow Series</a>
    </section>
  </section>

  <a href="https://github.com/smlisk0630" alt="GitHub" target="_blank">Github</a>

  <a href="https://trailblazer.me/id/slisk" alt="Trailhead" target="_blank">Trailhead</a>


</nav>
Questioner
smlisk0630
Viewed
0
Merlin Fejzuli 2020-11-28 22:42:47

冷冻豌豆答案的罗迪(Rody)解决了问题1。

对于问题2:你要相对于其上级对齐下拉内容的中心。为此,你需要将下拉内容向左移动一半,然后再向右移动一半。同样,下拉菜单元素需要相对放置,否则下拉菜单内容将对文档具有实际意义。要使下拉菜单内容可见,你需要使下拉菜单和导航栏溢出可见。

nav {
    overflow: visible;
}

.dropdown {
    position: relative;
    overflow: visible;
}

.dropdown-content {
    position: absolute;
    width: 250px;
    left: calc(50% - 125px);
}

之所以起作用,是因为你通过指定left来使dropdown-content的中心与dropdown的左侧对齐:-125px,因为你将其向左移动了dropdown-content宽度的一半。然后将其与下拉中心对齐,你需要添加50%,因为它的位置绝对正确,因此将使用父级宽度作为参考,而父级宽度的50%是父级中心。