Parametrized CSS classes

Something I just hate about CSS is that a class is static. Let's say I want to include a picture in a page and that depending on the picture I want to align it to the left with a 1px top border and a variable right border, of align it to the right with a 1px bottom border and a variable left border. And let's add that all images should have a 10px padding.

The obvious solution is to use something like this :

.images {padding:10px}
.left {float:left; border-top:1px solid black}
.right {float:right; border-bottom:1px solid black}

<img class="images left" style="border-right:5px solid black" src="image.png"/>

This is highly impractical. That's why I've been asking myself for quite some time why there is no parametrized classes in CSS. To clarify that, here is what I'd consider to be a good solution :

.images(pos,L) {
padding:10px;
float:[pos];
border-[!pos]:[L]px solid black;
border-[pos: left => top | right => bottom]: 1px solid black;
}

<img class="images(left,5)" src="image.png"/>

Inside the block {}, the brackets would indicate that the content has to be evaluated. With a few simple primitives, it may be quite powerful:

  • negation : [!var]. example : if [pos] = left then [!pos] = right
  • switch : [var: case1 => res1 | case2 => | res2 ...]

Moreover, something nice would be infinite level of nesting. Who has never been stuck while trying to style nested lists ? For example, let's say we want to print a list and that each level of the list should be half the size of it's parent, this is what we should write:

/* root */
li {font-size:2em};

/* recursion */
li li {font-size:[$1(font-size)/2]}

Here, $1 refers to the first pattern (the first li), and $1(font-size) is evaluated. With such a system, it would be easier to do more complex stuff. The question really is : why doesn't it exist ?

One Response to "Parametrized CSS classes"

Capt'n Fab says:

Mhh… tu peux déjà faire ça facilement côté serveur, pourquoi tu veux le faire faire par le client ?
D'une part les clients seront incompatibles (le client microsoft n'acceptera que des entiers en paramètres, le client mozilla demandera que les champs soient typés et la norme précisera que tous les arguments devraient être des chaînes de caractère).

Et puis il faut voir que ce genre de fonctionnalité ne serait utilisé que pour faire de petites pages Web, puisque dès que l'on passe à l'échelle en dessus, ce sont les templates et autres joyeusetés abstractisates qui sont utilisées.

Bref, les classes paramétrées, c'est pas pour demain.

Leave a Reply