css-selectorsless

Specify an attribute value using the parent selector in LESS?


Is is possible to use the parent selector in LESS to specify a value for a parent attribute selector?

I want the following output:

[some-attribute] {
    font-weight: normal;
}

[some-attribute~="bold"] {
    font-weight: bold;
}

Given this (obviously incorrect) example:

[some-attribute] {
    font-weight: normal;

    &~="bold" {
        font-weight: bold;
    }
}

Is something like this possible in LESS?

EDIT: For anyone who might be curious, I did try this abomination:

[some-attribute {

    &] {
        font-weight: normal;
    }

    &~="bold"] {
        font-weight: bold;
    }
}

I'm kind of glad it didn't work. I might have been tempted.


Solution

  • The parent selector (&) only holds a reference to an entire complex selector, with the option to extend the selector provided that you use the entire thing as a base:

    .one > .two {
        &::after, &::before {
            // Compiles to .one > .two::after, .one > .two::before
        }
        & + .three {
            // Compiles to .one > .two + .three
    
            &-suffix {
                // Compiles to .one > .two + .three-suffix
            }
        }
    }
    

    It cannot be used to reference a part of a compound or simple selector, in particular it cannot be used to reference just the attribute name in an attribute selector. You'll have to stick with vanilla CSS.

    The reason that abomination doesn't work is because both preprocessors expect all selectors in style rules to be valid; [some-attribute is not a valid selector. You could write a mixin and/or use selector interpolation, but it still has to result in a valid selector when used with a style rule, since the compiler can't assume that you won't be using the selector in its own set of style declarations (though of course, whether a preprocessor should be controlling the author in this way is up for debate...).