我正在尝试为导航栏中的一项创建下拉菜单。我基于此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>
冷冻豌豆答案的罗迪(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%是父级中心。
我已经用更新的屏幕截图和代码编辑了我的帖子。现在,对齐方式是正确的,但是下拉元素不再可见。
对不起,我忘记了导航栏也隐藏了它的溢出。我已经相应更新了我的答案。还要确保没有错别字,因为代码段中下拉列表的溢出属性设置为可见而不是可见。