I am still a newbie and I created a navigation bar for a website using html and css, the services tab has a dropdown list, but the list stays on display even if display is set to none. Can anyone please assist me in this problem. I have tried many things now and can’t seem to fix the problem. I added the code i used:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Navigation Bar with Dropdown</title>
<style>
body {
margin: 0;
font-family: Arial, sans-serif;
}
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
background: linear-gradient(to right, #6a1b9a, #2e7d32);
padding: 10px 20px;
border-radius: 30px;
}
.navbar ul {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex: 1;
justify-content: space-evenly;
align-items: center;
}
.navbar li {
position: relative;
}
.navbar a {
text-decoration: none;
color: #fff;
font-size: 16px;
font-weight: bold;
transition: color 0.3s ease;
}
.navbar a:hover {
color: #d1c4e9;
}
/* Dropdown Menu */
.dropdown {
display: none;
/* Hidden by default */
position: absolute;
top: 100%;
left: 0;
background-color: #6a1b9a;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
z-index: 1000;
width: max-content;
}
.dropdown li {
margin: 0;
}
.dropdown a {
display: block;
padding: 10px 20px;
white-space: nowrap;
color: #fff;
font-weight: normal;
text-align: left;
}
.dropdown a:hover {
background-color: #4a148c;
}
.navbar li:hover>.dropdown {
display: block;
}
</style>
</head>
<body>
<nav class="navbar">
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li>
<a href="#services">Services</a>
<!-- Dropdown Menu -->
<ul class="dropdown">
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a></li>
</ul>
</li>
<li><a href="#articles">Articles</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</body>
</html>
I have watched some videos on youtube and tried some existing code, but each time I try it with my own navbar, there is an issue.
2
Answers
The style for
.navbar ul
is targetting the.dropdown
element you’re trying to hide and hasdisplay: flex
set..navbar ul
has a higher specificity, so it overrides the style from.dropdown
.To fix this, you can change the style selector from
.navbar ul
to.navbar > ul
. By adding the>
, you are saying "Selectul
elements that are directly within the.navbar
element", rather than selecting any nested children matchingul
.The simple way, you just change class in your CSS
from .dropdown -> to .navbar .dropdown
code: