I
I
Ilya Myasin2015-09-24 16:02:44
css
Ilya Myasin, 2015-09-24 16:02:44

LESS: how to assign colors based on context?

Hey!
There is a modular system where parts of the front-end (blocks and containers) do not know anything about each other, and it is very desirable to "make friends" of them using CSS (LESS) of a specific theme without changing the HTML markup.
There is a "transparent" block in which the color of the text should change depending on the context, that is, on where this block is placed. If the container has a dark background, the text is light; if the background of the container is light, the text is dark.
The markup of the container does not contain an explicit indication of its "darkness" factor, I also want to regulate this from the styles. Ideally it should look like this:

.block {
    .color_main();
}
.block2 .title {
    .color_main();
}

header, footer {
    .is_dark();
}

The output should give:
block, 
.block2 .title {
    color:#000;
}

header .block, 
footer .block, 
header .block2 .title,  
footer .block2 .title {
    color:#FFF;
}

Is it possible to solve this problem only on LESS? I managed to collect all the selectors through &: extend - like this: codepen.io/dubrowsky/pen/zvKWPq (click "View compiled" in the "LESS" window). Now they need to be multiplied somehow. fly" (that is, go over document.styleSheets already in the browser), but this is not Feng Shui. I don’t want to fence post-processing either.
Any chances to implement or at least somehow get closer? Yes, I understand that there are nuances - for example, not all the blocks are "transparent", there are more than two "darkness" states, several nested layers with different backgrounds may appear, etc. - but these are all the details, I want to understand if there is a solution in principle, or I need to dig in the other direction.
Thank you = )
UPD: I added the label "BEM" because we sometimes use it. Interested in the opinion of BEM adherents, how to deal with this? Because according to the canon, there seems to be no "transparency", the block should not depend on the context, but instead, the modifier must be explicitly indicated on all blocks, that is, the markup must be changed. Or not?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Ineshin, 2015-09-24
@IonDen

You can for example like this:

.block {
    color: #fff;
    .title {
        color: #fff;
    }

    header &, footer & {
        color: #000;
        .title {
            color: #000;
        }
    }
}

N
nonlux, 2015-09-24
@nonlux

less:

.blocks(@col) {
  & .block {
    color: @col;
  }
}

.blocks(#fff);

.header, .footer {
  .blocks(#bbb);
}

css:
.block {
  color: #ffffff;
}
.header .block,
.footer .block {
  color: #bbbbbb;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question