2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

svgSpriteに色(fill)が効かない

Posted at

問題。

gulp-svg-spriteで作ったsvgSpriteにCSSのfillが効かない!
->全部真っ黒に...

原因!

元データのsvg自体にfillがついているとCSSが効かない。
なんだ簡単だ。すぐに解決できそう。

https://qiita.com/rinoside/items/65bd2f84751dc45585c1
https://qiita.com/sats/items/7060afe95c25b13b8c78
上記を参考にしました。

解決法としては、
①svg-spriteのプラグインのsvgoを使う。
②svg-cheerioを使う!

①のプラグインのsvgo

svgoとは
https://github.com/svg/svgo
svgをいろいろ軽量化してくれる。こりゃいいや。

↓書き方

const svgSpriteTask = () => {
    return gulp.src(`${paths.srcImg}/svg/*.svg`)
        .pipe(plumber())
        .pipe(svgSprite({
            mode: {
              symbol: {
                dest: 'svg',
                sprite: 'symbols.svg'
              }
            },
            shape: {
              transform: [
                {
                  // 下記にsvgoの設定を書いていく。
                  svgo: {
                    plugins: [
                      // ここでfill属性を排除
                      {removeAttrs:{attrs: 'fill'}}
                    ]
                  }
                }
              ]
            }
        }))
        .pipe(gulp.dest(`${paths.distImg}`))
};

バッチリですね!
gulpを走らせます!

svgoでもcheerioでもfillが消えない

コンパイル後のファイルでfill検索してみるとわんさか残ってます。あれれ..
その後cheerioもしてみるも消えない。

諦めかけてsvgファイルをよく見たら、style属性の中にfill記述が!!!
つまり...

styleも消す!

const svgSpriteTask = () => {
    return gulp.src(`${paths.srcImg}/svg/*.svg`)
        .pipe(plumber())
        .pipe(svgSprite({
            mode: {
              symbol: {
                dest: 'svg',
                sprite: 'symbols.svg'
              }
            },
            shape: {
              transform: [
                {
                  svgo: {
                    plugins: [
                      // これを追加することで<style>が消える
                      {removeStyleElement: true},
                      {removeAttrs:{attrs: 'fill'}}
                    ]
                  }
                }
              ]
            }
        }))
        .pipe(gulp.dest(`${paths.distImg}`))
};

これをgulpで走らせたら無事消えました。属性だと思い込んでたけど違った...
元ファイルをよくみることは大事ですね。灯台下暗し。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?