本文介绍了使用LESS为CSS/前置选择器设定作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一大堆CSS,我想范围"到特定的HTML块.我正在生成一个唯一的ID,然后将其设置在HTML块上,然后想用相同的ID包装CSS块,以使这些选择器无法匹配同级或父元素.我不知道CSS块的内容.给定一大堆CSS:

I have a chunk of CSS that I want to "scope" to a specific block of HTML. I'm generating a unique ID and then setting it on the block of HTML and then would like to wrap the chunk of CSS with the same ID so that those selectors can't match sibling or parent elements. I don't know the contents of the chunk of CSS. Given a chunk of CSS:

.container {
    background-color: black;
}

.container .title {
    color: white;
}

.container .description {
    color: grey;
}

我需要它像这样出来:

.theme0 .container, .theme0.container {
    background-color: black;
}

.theme0 .container .title, .theme0.container .title {
    color: white;
}

.theme0 .container .description, .theme0.container .description {
    color: grey;
}

有没有办法用LESS做到这一点?第一个选择器很简单,只需用'.theme0 {' + cssChunk + '}'包装CSS块.但是我还没有办法在所有选择器前加'.theme0'而不加空格.

Is there any way to do this with LESS? The first selector is easy, just wrap the CSS chunk with '.theme0 {' + cssChunk + '}'. But I haven't been able to figure out a way to prepend '.theme0' to all of the selectors without the space.

因此,我应该澄清一下,我们的意图是将这样的系统构建到我们的构建过程/依赖系统中.我们正在尝试将一堆css定义为一个react组件.我们正在尝试几种不同的方法,这只是其中之一.重点是,我们试图确定范围的CSS和HTML可以是任何东西,我们对此没有控制权或知识.通过在.uniqueID {之前添加}可以轻松实现第一个模式.这给出.uniqueID .someSelector {}.我想知道是否有可能做类似的事情但得到.uniqueID.someSelector {}吗?理想情况下,无需借助我们的范围系统知识就可以编写CSS的原始代码.

So I should clarify that our intentions are to build such a system into our build process / dependency system. We're attempting to scope a chunk of css to a react component. We have a couple different approaches we're trying out, this is just one of them. Point is, the CSS and HTML we're trying to scope could be anything, we have no control or knowledge of it. The first pattern can easily be achieved by prepending .uniqueID { and appending }. This gives .uniqueID .someSelector {}. I'm wondering if it's possible to do a similar thing but get .uniqueID.someSelector {}? Ideally without having to write the original chunk of CSS with knowledge of our scoping system.

推荐答案

假定组件样式位于单独的CSS文件中,即:

Assuming the component styles are in a separate CSS file, i.e.:

// component.css

.container {
    background-color: black;
}

.container .title {
    color: white;
}

.container .description {
    color: grey;
}

包装器代码可能是:

.theme0 {
    @import (less) "component.css";
    &.container:extend(.theme0 .container all) {}
}

这篇关于使用LESS为CSS/前置选择器设定作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 23:15