parent selector in less

2019-07-20 20:10发布

问题:

Normally in less to reference a parent selector is:

.parent {
    .grand-pa & {
       /* this rules will apply to: .grand-pa .parent {....}
       background: grey;
    }
}

What I'm trying to do is something similar. example code HTML:

    <div class="panel panel-parent">
        <div class="panel-child">
            {{content}}
        </div>
    </div>

Less code:

.panel {
    .panel-child {
        // some rules
        &.panel-parent & {  //<=== IS IT POSSIBILE SOMETHING LIKE THIS??
            // .panel.panel-parent .panel-child{...}
        }
    }
}

The only solution I have found is to repeat .panel-child:

.panel {
        &.panel-parent .panel-child {  //<=== Workaround
            // .panel.panel-parent .panel-child{...}
        }        
        .panel-child {
        // some rules
        }
    }
}

回答1:

The order of classes of the same element does not actually matter, i.e. .panel.panel-parent is equal to .panel-parent.panel (both will match <div class="panel panel-parent">), thus you can get what you need with just:

.panel {
    .panel-child {
        a: a;
        .panel-parent& {
            b: b;
        }
    }
}

instead.



标签: css less