简体   繁体   中英

How to make parent selector interpolated in the middle of nested selector in sass/scss

I'd like to get the result below using sass nesting

css

.box {...}
h3.box-title {...}

I tried code like this, but it causes an error.

sass

.box {
    h3.&-title {
        ...
    }
}

I'd like to know if there is any way to do this keeping sass nesting?

I know that it's not good to write HTML element on CSS, but I'm working on a project that I can't modify existing CSS and need to overwrite them.

Try this:

.box {
    @at-root h3#{&}-title {
        ...
    }
}

I used the sass interpolation #{} to compile expectedly the value of & , and @at-root to prevent the prefix .box (prevent resulting to .box h3.box-title because we want h3.box-title only - without the prefix .box )

Here's the captured result: 在此处输入图片说明

Anyway, I don't think this is a good practice to write sass/scss

.box

and

.box-title

are two different class names. Unless h3.box-title is a child of .box, honestly, there's no reason you should be nesting it.

Also & is used to look for additional class names. ie

.box {
 &.box-title {} 
}

would be

.box.box-title {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM