Issue
I want to change multiple divs' background color when the parent div is hovered over. What I'm basically doing is creating a hamburger menu out of 3 divs, and wanting to change its color from black -> white when hovered.
My current solution is
.burger_container:hover .bar1{
background-color: white;
}
.burger_container:hover .bar2{
background-color: white;
}
.burger_container:hover .bar3{
background-color: white;
}
Another thing i considered was giving them another class id, such as
<div class="bar bar3"></div> , and then being able to do
.burger_container:hover .bar{
background-color: white;
}
is there a better way to do this for multiple childs? My solutions seem clunky. Let me know if one of the solutions i've posted is deemed "the correct way to do it". Cheers,
Solution
If the three are the only children of their parent, you could use
.burger_container:hover > * {}
If they aren't, you could use
.burger_container:hover > [class^="bar"] {}
You don't need (and shouldn't use) classes as ids. Use ids as unique identifiers and classes as collection member identifiers. Both CSS and JavaScript are optimized for this paradigm.
Apart from this, your goal is to get the job done using as little code as possible, while keeping it readable and maintainable. that's why your version 1 is really bad, not only for being much longer, but also because if you wanted to later change the value you'd need to modify it in 3 places instead of just one. Following the same principle, if you find yourself wanting to add a class to all children of an element, you're better off adding a class to the parent and selecting with .yourClass > * where .yourClass is the parent selector and * is the child selector (you might want to use something more specific than any (*).
To apply all the above to your case, and to have the fastest code possible, if there is only one instance of this in all your page, this is what I think would be best practice:
#hamburger-icon > div {
background-color: #fff;
}
<div id="hamburger-icon">
<div></div>
<div></div>
<div></div>
</div>
Answered By - tao
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.