LoginSignup
0
0

More than 3 years have passed since last update.

scss で media query を遠くに書きたくないが、出力サイズも減らしたい

Posted at
style.scss
.title {
  color: red;
}

.text {
  color: blue;
}

@media #{pc} {
  .title {
    color: green;
  }

  .text {
    color: yellow;
  }
}

とか遠くに書くのは嫌だ。

なので

style.scss
.title {
  color: red;

  @media #{pc} {
    color: green;
  }
}

.text {
  color: blue;

  @media #{pc} {
    color: yellow;
  }
}

scss 使ってるならこう書きたい。

でも、コンパイルすると

style.css
.title {
  color: red;
}

@media screen and (min-width: 1000px) {
  .title {
    color: green;
  }
}

.text {
  color: blue;
}

@media screen and (min-width: 1000px) {
  .text {
    color: yellow;
  }
}

同じ media query が吐き出されてしまって、サイズが大きくなる

何かしらで postcss を使っているなら postcss-combine-media-query を使う

Nuxt で作ってるなら nuxt.config.js の build に追記する

yarn add -D postcss-combine-media-query
nuxt.config.js
export default {
  build: {
    postcss: {
      plugins: {
        'postcss-combine-media-query': {},
      },
    },
  },
};

そうすると

style.css
.title {
  color: red;
}

.text {
  color: blue;
}

@media screen and (min-width: 1000px) {
  .title {
    color: green;
  }

  .text {
    color: yellow;
  }
}

このようにまとまって嬉しい。

なお Nuxt だと、コンポーネントごとにしかまとまらないけど、全部バラバラになるよりはマシ。

0
0
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
0
0