search
LoginSignup
2

More than 1 year has passed since last update.

posted at

updated at

emotionの書き方色々

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')});
  }
`

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
What you can do with signing up
2