Reputation: 1893
I am trying to figure out the best way to accomplish reusing some of the nested styles in Less to prevent duplication, but I am not sure if I have found the best way.
Right now I have something like:
.category-link,
.caption-link {
background-color: @linkColour;
font-family: @linkFont;
max-width:2em;
a {
/* INNER LINK STYLES */
text-decoration:none;
white-space:nowrap;
/* ...INNER LINK STYLES CONTINUE... */
}
}
Now I want to apply those same inner link styles to the selector .action-link a
without applying the outer styles to .action-link
.
I get my intended output if I do it this way:
.inner-link-styles() {
/* INNER LINK STYLES */
text-decoration:none;
white-space:nowrap;
/* ...INNER LINK STYLES CONTINUE... */
}
.category-link,
.caption-link {
background-color: @linkColour;
font-family: @linkFont;
max-width:2em;
a {
.inner-link-styles;
}
}
.action-link a {
.inner-link-styles;
}
which doesn't require any duplication, but I'd prefer to keep those styles in their current location, where they are relevant, than to move them out to mixins.less
and increase complexity for the next developer to troubleshoot.
What felt intuitive, but is clearly wrong, was something like this:
.category-link,
.caption-link {
background-color: @linkColour;
font-family: @linkFont;
max-width:2em;
& a,
.action-link a {
/* INNER LINK STYLES */
text-decoration:none;
white-space:nowrap;
/* ...INNER LINK STYLES CONTINUE... */
}
}
but is there some other prefix I can apply to a selector to have it based absolutely, rather than relative to it's nesting level?
Upvotes: 1
Views: 53
Reputation: 89780
Absolute selectors can't be added within a nested block because once we nest it under another block, the inner selector is considered as a child of the outer one (like in the DOM) unless we add &.
to the selector (in which case, the inner one could be another class on the parent itself).
Using mixins or the :extend
feature are the best options for your case because you are assigning a set of common properties to multiple elements.
Since parent selector is known (it is either .category-link a
or .caption-link a
), you can extend the properties of that selector into .action-link a
also. This would extend only the properties of the inner link and not that of its parent.
I don't think this increases the complexity for the next developer to troubleshoot because changing the properties in the original .category-link a
will change the properties for .action-link a
also.
.category-link,
.caption-link {
background-color: blue;
font-family: Arial;
max-width:2em;
a {
/* INNER LINK STYLES */
text-decoration:none;
white-space:nowrap;
/* ...INNER LINK STYLES CONTINUE... */
}
}
.action-link {
a {
&:extend(.category-link a);
}
}
Upvotes: 1