SCSS extend a nested selector and override the nes

2019-01-06 19:06发布

Ok so I have a placeholder with a nested selector:

%block {
  .title {
    font-size:12px;
  }
}

I want to extend it and ADD to the .title class:

.superblock {
  @extend %block;
  .title {
    font-weight:bold;
  }
}

The answer I WANT is this:

.superblock .title {
  font-size: 12px;
  font-weight: bold; }

However, the answer I get is this:

.superblock .title {
  font-size: 12px; }

.superblock .title {
  font-weight: bold; }

Am I doing something wrong or is this just how it works? To clarify I want to merge it. If I add something directly inside the .superblock and add like another .superblock2 which also extends %block they merge without any problems.

标签: css sass
4条回答
太酷不给撩
2楼-- · 2019-01-06 19:20

This is pretty much it. SASS produces extended declarations separately.

And it has no functionality of grouping declarations by selector, it's not that smart.

But you need not worry that much about CSS cleanness. Modern web servers serve CSS gzipped, all duplication will be nicely compressed.

查看更多
叛逆
3楼-- · 2019-01-06 19:23

You can use a tools, I used it to clean the css https://github.com/addyosmani/grunt-uncss

"A grunt task for removing unused CSS from your projects with UnCSS."

查看更多
一夜七次
4楼-- · 2019-01-06 19:31

Sass has no functionality for "merging" duplicate selectors. You'll need to find another utility to do this after the CSS has been compiled.

The @extend directive isn't just a way to use classes in place of mixins (similar to LESS style mixin calls). Why @extend works the way it does becomes clear when you're extending normal classes instead of extend classes:

.block {
  font-size:12px;
}

.foo {
    @extend .block;
    font-weight: bold;
}

Output:

.block, .foo {
  font-size: 12px;
}

.foo {
  font-weight: bold;
}

Using an extend class just suppresses the emission of the original class name.

Now that you've seen why @extend works the way it does, do you still want what @extend offers? If the answer is no, then you need to use a mixin:

@mixin block {
    // styles
    .title {
        font-size: 12px;
        @content;
    }
}

.superblock {
    @include block {
        font-weight: bold;
    }
}

Output:

.superblock .title {
  font-size: 12px;
  font-weight: bold;
}
查看更多
Bombasti
5楼-- · 2019-01-06 19:33

LESS can do that. However you would write:

.superblock {
  .title {
    .block .title;
  }
}

Not sure if it works with @extend too.

查看更多
登录 后发表回答