SCSS and “:host([active])”

杀马特。学长 韩版系。学妹 提交于 2019-12-22 18:26:21

问题


I need such construction in scss:

:host {
    background: #fff;

    &([active]) {
        background: #000;
    }
}

meaning output like:

:host {
    background: #fff;
}
:host([active]) {
    background: #000;
}

But I can't get it working any way I've tried. Is there any way to escape parentheses I don't know or something not overcomplicated?

Just inserting piece of raw css like `code` in CoffeeScript would be great, but I do not see anything like this in documentation.


回答1:


If you want to use this shadow DOM selectors in the scss files you cant use :host(<selector>) nested right now. A workaround is to repeat :host for each selector you want to use.

SCSS:

:host {
    background: #fff;
}
:host([active]) {
    background: #000;
}

CSS (the same):

:host {
  background: #fff;
}

:host([active]) {
  background: #000;
}

You could try it here: http://sassmeister.com/




回答2:


Unfortunatly sass still doesn't support this. I made an additional workaround to support nested state selectors on :host

Assuming you also use gulp-sass to compile your sass to css you can do the following:

npm install gulp-replace

Next add the following to the top of the gulp script that compiles your sass:

var replace = require('gulp-replace');

And add the following to your sass compile pipe:

.pipe(replace(':host:hover', ':host(:hover)'))

Now you can use the following construct in your sass:

Sass

:host {
    &:hover {
        color: red;
    }
}

The replace function will change your css to look like this:

CSS

:host(:hover) {
  color: red;
}

Your gulp script should look something like this:

Gulp

var gulp = require('gulp');
var replace = require('gulp-replace');
var sass = require('gulp-sass');

gulp.task('sass', function () {
    return gulp.src('./src/sass/**/*.scss')
        .pipe(sass({
            outputStyle: 'expanded',
            precision: 10,
        }))
        .pipe(replace(':host:hover', ':host(:hover)'))
        .pipe(gulp.dest('./dist/css'));
});

You can add more states by expanding the replace part of your gulp script.



来源:https://stackoverflow.com/questions/25825541/scss-and-hostactive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!