Given this markup:
<div class="parent" data-active="typeA">
<div class="child" data-show="typeA">Show only when parent=typeA</div>
<div class="child" data-show="typeB">Show only when parent=typeB</div>
<div class="child" data-show="typeC">Show only when parent=typeC</div>
</div>
I'm trying to write a globally applicable LESS rule that only displays a child when its data-show
attribute matches the parent's data-active
attribute.
Something like this:
.parent {
.child { display:none; }
&[data-active="?"] .child[data-show="?"] { display:block; }
}
...where ?
should not be a fixed value, but a condition that applies no matter the value, as long as they are the same.
Any ideas?
As LESS gets compiled to CSS and there is no generic approach for doing this in CSS, I only come up with a solution that requires you to know every possible type.
.parent {
.child { display: none; }
&[data-active="typeA"] {
.child[data-show="typeA"] { display: block; }
}
&[data-active="typeB"] {
.child[data-show="typeB"] { display: block; }
}
&[data-active="typeC"] {
.child[data-show="typeC"] { display: block; }
}
}
Depending on your preferences and to avoid redundancy you could also define a function for adding the different types.
.parent {
.child { display: none; }
.addType("typeA");
.addType("typeB");
.addType("typeC");
}
.addType(@type) {
&[data-active="@{type}"] {
.child[data-show="@{type}"] { display: block; }
}
}
And if you want to make this even more generic, you could define an array of types and call .addType
for each of the types like this:
@types: "typeA", "typeB", "typeC";
.parent {
.child { display: none; }
.-(@i: length(@types)) when (@i > 0) {
@type: extract(@types, @i);
.addType(@type);
.-((@i - 1));
} .-;
}
.addType(@type) { /* see above */ }