Sh...">

Use unknown values ​​as selectors in Less

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 am trying to write a globally applicable LESS rule that only displays a child when its attribute data-showmatches the parent attribute data-active.

Something like that:

.parent {
    .child { display:none; }
    &[data-active="?"] .child[data-show="?"] { display:block; }
}

... where ?it should not be a fixed value, but is a condition that applies regardless of the value if they are the same.

Any ideas?

+1
source share
1 answer

Since LESS is compiled in CSS and there is no general approach for this in CSS, I only offer a solution that requires you to know all the possible types.

.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; }
    }
}

.

.parent {
    .child { display: none; }
    .addType("typeA");
    .addType("typeB");
    .addType("typeC");    
}

.addType(@type) {
    &[data-active="@{type}"] {
        .child[data-show="@{type}"] { display: block; }
    }
}

, .addType :

@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 */ }
+1

Source: https://habr.com/ru/post/1667392/


All Articles