Search code examples
less

How to inherit position from parent selector when using "&-..." syntax in LESS?


I have some code that is similar to this:

.map-container {
    position: relative;

    .map {
        width: 100%;
        height: 100%;
    }

    .point {
        position: absolute;
        color: red;

        &-blue {
            color: blue;
        }
    }
}

It allows me to create points on an image of a map using inline styles to specify specific locations. The intention of this code is that ".point-blue" maintains the absolute positioning, but changes the color. I essentially want to inherit traits from what is specified in the parent selector of "&-blue".

The actual result is that ".point-blue" is not absolutely positioned unless I also specify absolute positioning under that selector as well. I can either add that or change every point element to have both the "point" and "point-blue" classes. I want to be able to have ".point-blue" imply ".point" as well.


Solution

  • position: absolute is never heritable in CSS, so I don't think you can do this in Less, either. Absolute positioning creates a new, separate stacking context whenever it is applied; if it were inherited with parent selectors in CSS preprocessors like Less or Sass, it would probably result in lots of unexpected layout breakage.

    You'll need to explicitly declare the position value in the .point &-blue selector.