Looking at this example:
If you click "Package" the entire submenu and red background should not be shown.
EDIT 1:
I should add that I experimented using :has
and :target
in various combinations to set change it to display: none
. That did not work.
CodePudding user response:
I think that technically the answer to your question is yes, it is possible, but actually no - at least not in a way your page will continue functioning normally afterwards. Let me explain:
If you were to use anchor elements for our subnav links/buttons you could use a combination of the the :visited
and :has
pseudo classes to set the submenu's display to none (display: none;
) and the main menu's color to the original color. However, I believe this will mean you won't be able to make the submenu appear again unless you were to somehow cancel the "visited" status of the anchor element that was clicked which if possible, will most certainly include the use of JS anyway...
CodePudding user response:
One way to make a submenu disappear when it is clicked is to use the :active pseudo-class in CSS. The :active pseudo-class is applied to an element when it is being activated, typically by the user clicking or tapping on it.
For example, you can use the :active pseudo-class to toggle the visibility of a submenu by setting the display property of the submenu to none when it is active:
.submenu {
display: none;
}
.submenu:active {
display: block;
}
Then, you can add the .submenu class to your submenu element, and the .submenu:active style will be applied to the element when it is clicked, causing the submenu to be displayed. When the user clicks anywhere else on the page, the :active state will be removed from the submenu element and the display property will be set back to none, causing the submenu to disappear.
Here's an example of how you might use this technique in a simple HTML and CSS menu:
<style>
.menu {
display: flex;
}
.menu li {
list-style: none;
}
.submenu {
display: none;
}
.submenu:active {
display: block;
}
</style>
<ul >
<li>
<a href="#">Menu item 1</a>
</li>
<li>
<a href="#">Menu item 2</a>
<ul >
<li><a href="#">Submenu item 1</a></li>
<li><a href="#">Submenu item 2</a></li>
<li><a href="#">Submenu item 3</a></li>
</ul>
</li>
<li>
<a href="#">Menu item 3</a>
</li>
</ul>
This approach works well for simple menus, but it may not be suitable for more complex scenarios where you need to toggle the visibility of multiple submenus or perform other actions on click. In those cases, you may need to use JavaScript to achieve the desired behavior.
Now you can see how it works and how can you implement in your project the submenu. Good Luck!