Let’s say I have three div elements with classes a, b, and c, respectively. I want to use css to toggle the display of these elements between none and block, depending on whether or not a parent element has a class of current or is hovered. The elements always toggle together, never individually.
I can a) toggle the display on the elements individually, or I can b) wrap them in a fourth div that is otherwise non-functional and toggle display on that element instead.
So, for instance, it’s this:
<li>
<div class="a"></div>
<div class="b"></div>
<div class="c"></div>
</li>
li > .a,
li > .b,
li > .c {
display: none;
}
li:hover > .a,
li.current > .a,
li:hover > .b,
li.current > .b,
li:hover > .c,
li.current > .c {
display: block;
}
versus this:
<li>
<div class="wrap">
<div class="a"></div>
<div class="b"></div>
<div class="c"></div>
</div>
</li>
li > .wrap {
display: none;
}
li:hover > .wrap,
li.current > .wrap {
display: block;
}
There’s an obvious code-cleanliness difference in the css, at the expense of some additional html structure, but I think the net is in favor of using the wrapper.
I’m wondering if there are any other benefits or costs, such as browser performance, one way or the other between the two options.
Actually, you don’t have to do either :). You’re using CSS!! Consider the following:
Now, you can keep your styling elements for
a,b,c. By adding a simple CSS style, you can cover both of your sets of needs quickly and easily. Additionally, its abstracted, so you could use it in more places, when needed. No addition of DOM elements necessary and no real changes to your current styling code fora,b, andc. Furthermore, your switch doesn’t even have to be anli.Additional Information on CSS classes
Elements may be of more than one class. By utilizing this, you can separate pseudo-functionality from look inside your CSS. When utilizing multiple classes, the browser will combine the rules of both to complete its style.
Consider the following:
bodyelement will have whatever html positioning, and overall document overrides.articleclass would have whatever presentation styles you might need.twocolumnswould have whatever layout parameters your require.You may provide individual or combination styles, like so:
Learning to do things in this way has a number of benefits. It allows you to abstract functionality, layout and presentation elements easier allowing you to “port” either to other web projects you might have. It allows you to find what works cross-browser more effectively for more unified look and feel. It also reduces the tendency to accidentally tweak rules that might not be related to your issue. Finally, it reduces your dependency on extraneous DOM elements allowing you to keep your performance.
Hope this helps.
FuzzicalLogic