I'm currently elaborating a variation on Nicole Sullivan's OOCSS grids module that only requires a single container class to determine the layout of immediate descendants. I'm aware this bears the caveats of only working in CSS3 supporting browsers.
Here's an example of the difference:
Vanilla OOCSS grids rule:
.unit1of4 {
width: 25%;
}
My reduced grids rule:
.line > :nth-child(1):nth-last-child(4),
.line > :nth-child(2):nth-last-child(3),
.line > :nth-child(3):nth-last-child(2) {
width:25%;
}
Another significant caveat is the assumption that an element's fractional size is determined exclusively by its number of siblings — whereas that's the essential point of this code (to enable leaner HTML without explicit sizes all over the place), there will be exceptions where one might wish to have disproportionate widths.
Because of the specificity of my selectors, I can't simply stick the OOCSS module back in: specifying a unitXofY
class in the HTML would be done specifically to supersede the default assumption, but in practice my selectors are stronger and would always override the specified class.
What I'm looking for is the tersest or most elegant way to supersede these selectors without limiting the practical effect of the specificity. That is to say, it must not make any assumptions about the selected element other than its class that will not always be correct.
The best I can come up with is :nth-child(n)
, in that it resolves to a meaningless statement which translates into plain English as 'a child element', which will always be the case of nested fractions. The code to implement this looks like this:
.line > :nth-child(1):nth-last-child(4),
.line > :nth-child(2):nth-last-child(3),
.line > :nth-child(3):nth-last-child(2),
.size1of4:nth-child(n):nth-child(n):nth-child(n) {
width:25%;
}
The selector is specified 3 times over such that it trumps the previous selectors by 1, meaning it can also trump the next rule governing .size1of5
.
As a SASS mixin:
Because this is a verbose hack, I've packaged it up as a SASS mixin:
@mixin increase-specificity( $depth: 1 ) {
$sel : '';
@while($depth > 0) {
$sel : $sel + ':nth-child(n)';
$depth : $depth - 1;
}
&#{$sel} {
@content;
}
}