Using The Cascade
In this post, I am going to explain the benefit of exploiting the 'cascading' part of CSS to solve everyday styling problems more efficiently and effectively. The example problem I have chosen is that of clearing content after floats. For those not familiar with the problem that necessitates clearing, it effects elements that appear directly after floated elements in the markup. These elements are pulled up the page to rest behind the floated element(s), obscuring their content and generally making a mess of the page.
The problem is easily solved by applying the clear:both
declaration to the obscured element. This forces the element down the page so that it appears below (not behind) the content preceeding it:
.get-down-damn-you {
clear:both;
}
However, a problem occurs when your layouts begin to evolve and new content is created or elements are moved around: You have to keep checking that the right elements have clear:both
applied. Worse still, a content manager not familiar with the problem might replace the content under a float with different content which lacks the get-down-damn-you
class and panic because they have no idea why the page has gone awry.
A solution
You could make use of the 'cascade' (read: Cascading Style Sheets) and declare all relevant elements to carry the clear:both
property as a default. For example:
div {
clear:both;
}
This is a safe provision since clear:both
does not have any noticeable effect on elements in regular circumstances. In fact, the only elements it adversely affects are the floated elements themselves. Not to worry, we can use clear:none
to override this …
#floated-thing {
float:left;
clear:none;
}
Conclusion
By making use of 'the cascade' we can place ourselves in a position where we only have to address the exceptions and, since we have to write out the CSS for each of our floated elements anyway, what's the bother with throwing in just one more property?
Using less.js we could take our forward planning one step further. First we would make two classes - one for a left float and one for a right float:
.floated-left {
float:left;
clear:none;
}
.floated-right {
float:right;
clear:none;
}
When we define our new element's styles, we can use a 'mixin' to include the properties from one of our classes in one line of CSS:
.white-on-black {
width:200px;
background-color:#000;
color:#fff;
.floated-left; /* the 'mixin' */
}
Now that we have binded our 'float' and 'clear' properties together, we no longer need to remember that one requires the other.