目次

この記事はQiitaに投稿していたものです。 このブログに自身のアウトプットをまとめるための再投稿です。 また、この記事の執筆は2020年12月22日なので現状の状態と異なる可能性があります。

emotionとは?

emotion-Introduction CSS in JSをするためのライブラリ

基本的な書き方

<style>
.hoge{
  color: red;
}
</style>
import { css } from 'emotion'

const hoge = css`
  color: red;
`

疑似クラスを置き換える

<style>
.hoge{
  color: red;
}
.hoge:hover{
  color:green;
}
</style>
import { css, cx } from 'emotion'

const hoge = css`
  color: red;
  &:hover {
    color:green;
  }
`

疑似要素を置き換える

<style>
.hoge{
  color: red;
}
.hoge::before{
  color:green;
}
</style>
import { css, cx } from 'emotion'

const hoge = css`
  color: red;
  &::before{
    color:green;
  }
`

composesを置き換える

<style>
.hoge{
  margin: auto;
  padding: 0;
}
.hogehoge{
  composes: hoge;
  padding-bottom: 10px;
}
</style>
import { css, cx } from 'emotion'

const hoge = css`
  margin: auto;
  padding: 0;
`
const hogehoge = cx(hoge, css`
  padding-bottom: 10px;
`)

keyframeを置き換える

<style>
.square {
  animation: loader 2s infinite ease;
}
@keyframes loader {
  0% {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(180deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
import { css, keyframes } from 'emotion'

const loader = keyframes`
  0% {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(180deg);
  }
  100% {
    transform: rotate(360deg);
  }
`
const square = css`
  animation: ${loader} 2s infinite ease;
`

Modernizrを使っている場合

<style>
.hoge{
  background-image: url('~assets/img/hoge.webp');
}
.no-webp .hoge{
  background-image: url('~assets/img/hoge.png');
}
</style>
import { css } from 'emotion'
const hoge = css`
  background-image: url('~assets/img/hoge.webp');
  .no-webp & {
    background-image: url(${require('~/assets/img/hoge.png')});
  }
`