Studying and testing HTML, CSS and JavaScript codes required for the nav menu to turn into a toggle menu on mobile screens.
Currently having trouble due to nav
menu showing page names without requiring the toggle menu button to be pressed first.
function toggleMenu() {
var menu = document.getElementById("menu");
menu.classList.toggle("active")
}
nav {
background-color: #333;
color: whitesmoke;
}
#menu {
display: flex;
justify-content: center;
list-style-type: none;
padding: 0;
margin: 0;
}
.menu {
display: flex;
justify-content: center;
list-style-type: none;
padding: 0;
margin: 0;
background-color: black;
position: relative;
}
.menu li a:hover {
color: black;
background-color: white;
}
.menu li {
margin-right: 20px;
}
.menu li a {
color: white;
text-decoration: none;
padding: 10px 15px;
display: block;
}
.menu-toggle {
display: none;
}
#menu li {
padding: 12px;
}
#menu li>a {
color: white;
text-decoration: none;
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
font-weight: bold;
font-size: medium;
padding: 10px;
}
#menu li>a:hover {
background-color: white;
color: black;
border-radius: 20px 20px 20px 20px;
}
@media only screen and (max-width: 768px) {
.menu-toggle {
display: block;
text-align: right;
padding: 10px;
cursor: pointer;
color: white;
position: relative;
background-color: black;
}
.menu {
display: none;
flex-direction: column;
align-items: center;
width: 100%
}
.menu li {
margin: 10px 0;
}
.menu.active {
display: flex;
}
.menu-toggle {
display: block;
text-align: right;
padding: 10px;
cursor: pointer;
color: white;
position: relative;
background-color: black;
}
}
<div class="menu-toggle" onclick="toggleMenu()">
<span>☰ Menu</span>
</div>
<nav>
<!--questo è il menù-->
<ul id="menu" class="menu">
<li><a href="#">HOME</a></li>
<li><a href="#">ABOUT</a></li>
<li><a href="#">CONTACTS</a></li>
</ul>
</nav>
Can you kindly have a quick look and report me what am I supposed to edit in order to make "HOME, ABOUT, CONTACTS" disappear when screen width is under 768px, so they can popup only after clicking the toggle menu symbol?
I checked w3schools turorials and everything looks fine on my code. But I must have missed something.
3
Answers
The CSS for id
#menu
overwrites styles for the class.menu
.To fix this just remove the entire
#menu { … }
part from the styles as everything here is already applied to the.menu
class later.Edited CSS:
You’re facing an issue with your specificity weight.
Specificity:
CSS line 6:
This sector has a specificity of
1.0.0
Within your media queries you have:
which has a specificity of
0.1.0
The higher specificity of an element with an id will beat that decleration so ti will never apply. Change the classes
.menu
to#menu
to make the specificity equal!You need to change the:
Inside:
@media only screen and (max-width: 768px)
to be:
(refer to id and not to class)