W3C home > Mailing lists > Public > www-style@w3.org > January 2012

@with -- DRY syntax for nesting selectors

From: Marat Tanalin | tanalin.com <mtanalin@yandex.ru>
Date: Mon, 09 Jan 2012 17:29:01 +0400
To: www-style@w3.org
Message-Id: <746501326115741@web45.yandex.ru>
One of features most demanded by web developers is grouping/nesting selectors DRY way.

Current CSS syntax is far from being DRY since it forces web developers to inevitably repeat themselves again and again and again by repeating same parts of selectors multiple times.

I propose following convenient syntax:

    @with (selectors) {
        rules and @with's

    * selectors means a selector or multiple comma-separated selectors;
    * rules are CSS rules;
    * @with's are nested @with at-rules.

Let's consider following example CSS code:

    #example .foo .bar {background: #ccc; }

    #example .foo .bar > DIV,
    #example .foo .bar > P {color: #00f; }

    #example .foo .bar > DIV > A,
    #example .foo .bar > DIV > STRONG {font-style: italic; }

    #example .foo .bar > DIV SPAN {color: #a00; }

With the proposed syntax, the code would get more DRY, compact, readable, and eventually much more maintainable:

    @with (#example .foo .bar) {
        :this {background: #ccc; }

        :this > DIV,
        :this > P {color: #00f; }

        @with (:this > DIV) {
            :this > A,
            :this > STRONG {font-style: italic; }

            SPAN {color: #a00; }

As you can see, :this pseudoclass points to selector of immediate containing @with and is used to attach declarations to @with selector itself as well as to use in conjunction with child combinator (>). Descendant selectors do not need for :this since they are automatically resolved in context of subject selectors of their corresponding @with.

We actually could use even more DRY/compact syntax where :this is implied:

    @with (#example .foo .bar) {
        {background: #ccc; }

        > DIV,
        > P {color: #00f; }

        @with (:this > DIV) {
            > A,
            > STRONG {font-style: italic; }

            SPAN {color: #a00; }

It'd perfectly OK for me, but is not as critical (though would be desirable anyway) as conceptual ability to prevent repeating selectors as such.

Compared with existing nonstandard solutions like LESS or SASS, the syntax proposed above avoids mixing declarations (property/value pairs) and rules on same nesting level (such mixing is generally a bad idea, and this is implicitly proved out, for example, by the fact that we don't have this in CSS standard so far).

Received on Monday, 9 January 2012 13:32:01 UTC

This archive was generated by hypermail 2.4.0 : Friday, 25 March 2022 10:08:09 UTC