This content originally appeared on @mdo and was authored by Mark Otto
Cascading styles is at the core of CSS—hell, it’s in the name—but experience has shown that building systems with too many cascading styles can be detrimental. Some times it’s completely necessary to just stop the cascade.
Let’s take the modal of Bootstrap as an example.
Notice how we namespace classes at key levels—each class name begins with modal-
as a prefix. Class name prefixing makes our code more durable and easier to maintain, but it also better enables us to scope styles to only the relevant elements.
Consider this snippet of CSS used to style the modal heading:
By using this generic selector, we inadvertently change the styles of the h3
in the .modal-body
. We’ve introduced an instance of cascading styles—any h3
throughout the .modal
will be center aligned. Therefore, if we wanted the other instances of h3
to be left-aligned, we’d have to override our brand new styles with something like this:
It’s worth noting that this example isn’t without its flaws, but that’s the point. With a little more time and thought, one can easily avoid this problem, avoiding extra lines of code and more complications in the overall system. Had we done things differently and altered our selector, our CSS might look like this:
By limiting the scope of a selector, we reduce the likelihood that we need additional code down the line by strengthening each component and limiting the effects of their styles. If done right, we can create an entire system of independent and durable, yet still flexible, components. It’s a promising approach I think, but one not to employ with an iron first.
Some CSS should be allowed to cascade. Base typography, links, and the such are prime examples of something not to redeclare over and over again. This would only serve to weigh down a project and make it even more unmanageable. Instead, the goal as always is to strike a balance.
Find ways to isolate components and make them more durable by limiting the scope of their CSS. You’ll discover that components can be more easily rearranged without causing adverse effects and the amount of code necessary will likely decrease.
This content originally appeared on @mdo and was authored by Mark Otto
Mark Otto | Sciencx (2012-03-02T00:00:00+00:00) Stop the cascade. Retrieved from https://www.scien.cx/2012/03/02/stop-the-cascade/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.