Here is the code you have utilized:
.fontbutton button:hover .fontmenu .fontlist{ }
Why It Won't Work
Interested in knowing why this won't work? Continue reading on as I provide an explanation. But first, let's explore what will work.
Let's experiment with different selectors:
.fontbutton:hover + .fontlist {}
This WILL be effective
Witness it in action below:
.fontmenu .fontlist {
bottom: 30px;
display: none;
}
.fontbutton:hover + .fontlist {
display: block;
}
/* Avoid targeting the parent fontmenu div and instead target siblings like fontbutton and fontlist.
Use the + selector to avoid the browser mistaking fontlist for a child of fontbutton */
<div class="fontmenu">
<div class="fontbutton">
<button>fonts</button>
</div>
<div class="fontlist">
<div onclick="font(1)">Arial</div>
<div onclick="font(2)">Courier</div>
<div onclick="font(3)">Verdana</div>
<div onclick="font(4)">sans</div>
</div>
</div>
Note how the list appears even by hovering to the right of the button. This occurs because we are targeting the div element fontbutton, not the <button>
element. As a result, the browser displays the list when we hover over the div, not the button.
Solution
A slight HTML adjustment is required.
.fontmenu .fontlist {
display: none;
}
button:hover + .fontlist {
display: block;
}
<div class="fontmenu">
<button>fonts</button>
<div class="fontlist">
<div onclick="font(1)">Arial</div>
<div onclick="font(2)">Courier</div>
<div onclick="font(3)">Verdana</div>
<div onclick="font(4)">sans</div>
</div>
</div>
By eliminating the .fontbutton class and positioning the <button>
as a sibling of .fontlist
, the list will now only be visible when hovering over the button.
You may suggest adding more selectors to your CSS. However, this wouldn't work as there's no direct way to target <button>
and then move down to the separate .fontlist
within a different div.
.fontbutton > button:hover ? .fontmenu > .fontlist{ }
The issue lies with the ?
placeholder.
- We initially descend to
.button
.
- We then ascend to
.fontbutton
.
- Add a
+
selector and transition to .fontmenu
.
- Finally, reach
.fontlist
by descending further.
Once we've descended to .button
, we cannot return upwards to .fontbutton
.
Lack of Parent Selector in CSS
Hence, such targeting methods are not feasible using CSS.