Reputation: 55
I'm trying to made a burger menu with CSS/JS.
I have a navbar (nav) menu that display like this in computers:
And in Burger Menu when the resolution is less than 768 px (resolutions for tablet and devices that is under this resolution) like this:
The burger menu button is hidden (with display:none) when we are in computers, but I make it appear when the resolution is (>768px), and it shown, and with Javascript I grab this button and add event Listener to it.
When we click on the burger button, a list menu ( element) have to appear form the right to left with translateX(0%), because I made the list initially transform:translateX(-100%) to go out of the screen (I add to body an overflow-x:hidden to hide the excess and to provide a horizontal scrollbar, anyway)..
The style for the ul.nav_links initially:
position: absolute;
right: 0;
top: 8vh;
height: 92vh;
background-color: rgb(68, 122, 122);
display: flex;
flex-direction: column;
width: 50%;
transition: transform 2s;
transform: translateX(100%);
The class I want to add (just to return to 0%):
// Class to add in JavaScript
.nav_active {
transform: translateX(0%);
}
The Js code:
//grabbing the burger button
let burger=document.querySelector(".burger");
//grabbing the ul element with class (nav_links)
let nav=document.querySelector(".nav_links");
//Add the listener to burger button, that have to toggle the class "nav_active"
burger.addEventListener("click",()=>{
nav.classList.toggle("nav_active");
})
But for some reason the class (named:nav_active), is adding correctly to the (I use the devtools of Chrome and the class toggle each time I click on it, i can see the class add and remove to), but the transform:translateX(0%), it doesn't works.
I don't know why ?
Upvotes: 1
Views: 251
Reputation: 4333
The problem is CSS specificity; the class for ul.nav_links
will take higher priority than just a .nav_active
class.
The order of cascade is as follows: (copied from w3schools link below)
<h1 style="color: #ffffff;">
.So the .nav_active
is being overwritten by the class of higher specificity, meaning element + class in this example. If they were the same level of specificity, (ul.nav_links
and ul.nav_active
, for example), then the one that is defined LATER is the one that takes preference.
You would likely find that changing the .nav_active
class to ul.nav_active
or even ul.nav_links.nav_active
would be enough to make the active class apply correctly.
See https://www.w3schools.com/css/css_specificity.asp for some details on how to better understand / calculate the specificity level.
Upvotes: 1
Reputation: 11
I'm not sure but can you try this?
.nav_active {
transform: translateX(0%) !important;
}
Upvotes: 1