为什么当我移开指针时下拉菜单消失?感觉好像我没有将:hover
应用于正确的元素,但是我无法弄清楚。有没有一种方法可以快速找出:hover
应该在哪里?
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
font-family: Arial, Helvetica, sans-serif;
}
nav {
display: flex;
justify-content: space-around;
align-items: center;
min-height: 8vh;
background-color: #fbb2c3;
}
.nav-links {
display: flex;
justify-content: space-around;
width: 45%;
}
.nav-links li {
list-style: none;
position: relative;
}
.nav-links a {
text-decoration: none;
letter-spacing: 0.5px;
font-weight: bold;
}
.nav-links li ul {
visibility: hidden;
opacity: 0;
min-width: 10rem;
position: absolute;
margin-top: 2rem;
left: 0;
display: none;
}
ul li:hover>ul,
ul li ul:hover {
visibility: visible;
opacity: 1;
display: block;
}
<body>
<nav>
<ul class="nav-links">
<li><a class="dropdown" href="#">portfolio</a>
<ul class="dropdown-content">
<li><a href="#">littérature</a></li>
<li><a href="#">sous-titrage</a></li>
<li><a href="#">web</a></li>
</ul>
</li>
<li><a href="CV.html">parcours</a></li>
<li><a href="Intro.html">profil</a></li>
<li><a href="Contact.html">contact</a></li>
<li><a href="Contact.html">carte de visite</a></li>
</ul>
</nav>
</body>
您发生的问题是因为您将鼠标悬停在链接和下拉菜单之间有一个空格。
您正在右侧元素上使用:hover。在您的孩子UL和您的父链接之间有2rem的余量。这意味着在这个范围内,您在父母之外,在孩子之外。您需要让父母或孩子填补这个空白。在下面的修改后的代码段中,您将看到我将子UL的顶部边缘变成了填充。填充位于UL内部,而余量位于UL外部。
我提出的解决方案不是唯一可以解决此问题的解决方案,除了此功能之外,还取决于您要实现的视觉效果。
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
font-family: Arial, Helvetica, sans-serif;
}
nav {
display: flex;
justify-content: space-around;
align-items: center;
min-height: 8vh;
background-color: #fbb2c3;
}
.nav-links {
display: flex;
justify-content: space-around;
/*width: 45%; Commented out because of how this shows in the SO iframe */
}
.nav-links li {
list-style: none;
position: relative;
}
.nav-links a {
text-decoration: none;
letter-spacing: 0.5px;
font-weight: bold;
}
.nav-links li ul {
visibility: hidden;
opacity: 0;
min-width: 10rem;
position: absolute;
padding-top: 2rem; /* PROPOSED SOLUTION */
left: 0;
display: none;
}
ul li:hover>ul,
ul li ul:hover {
visibility: visible;
opacity: 1;
display: block;
}
<body>
<nav>
<ul class="nav-links">
<li><a class="dropdown" href="#">portfolio</a>
<ul class="dropdown-content">
<li><a href="#">littérature</a></li>
<li><a href="#">sous-titrage</a></li>
<li><a href="#">web</a></li>
</ul>
</li>
<li><a href="CV.html">parcours</a></li>
<li><a href="Intro.html">profil</a></li>
<li><a href="Contact.html">contact</a></li>
<li><a href="Contact.html">carte de visite</a></li>
</ul>
</nav>
</body>