Search code examples
htmlcsshoverdropdown

How do you have multiple buttons but only one has a hoverable dropdown in html?


I have been puzzled for a while. I am making a personal website with multiple navigation buttons including one dropdown menu. The dropdown menu should be triggered when the cursor hovers over the about button. I used W3School's code as part of the foundation. I have tried to create one myself however, when I hover over any button the menu triggers. I played around with using and using but neither was successful. I tried also creating a second but then I ran into another issue where I could not get the buttons (Gallery and Contact) to sit next to the other button (About). Below is the HTML and further is the CSS.

<nav class="dropdown">
<button class="about" href="about.html">About </button>
<button class="gallery" href="gallery.html">Gallery </a>
<button class="contact" href="contact.html">Contact </a>
<div class="dropdown-content"> 
    <a href="achievements.html">Achievements </a>
    <a href="education.html">Education </a>
    <a href="hobbies.html">Hobbies </a>
    <a href="career.html">Career </a>
</div>
.dropdown{
   font-size: 22px;
   font-family: "Arvo", serif;
   font-weight: bold;
   text-align: right;
   position:relative;
 } 
/* Dropdown Content (Hidden by Default) */
.dropdown-content {
  display: none;
  position: relative;
  background-color: #f1f1f1;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;

 }
 /* Links inside the dropdown */
  .dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;

 }.dropdown-content a:hover {
   background-color: #ddd;
 }
.about:hover .dropdown-content {
     display: block;

   }
.about:hover {background-color: transparent;

 }

Solution

  • You need to update the CSS. The dropdown-content is not a child of .about so doing .about:hover .dropdown-content wont work. You need to use General Sibling Selector

    Update it to .about:hover ~ .dropdown-content

    EDIT

    You also have an issue with your HTML you are opening button tags but closing a tags update them and it should work