LoginSignup
19
7

More than 3 years have passed since last update.

Material UIをTailwind CSSのスタイルで上書きする方法

Last updated at Posted at 2021-03-02

結論から言うと、Tailwind CSSの設定ファイルにimportant: trueを追記します(公式)。

tailwind.config.js
module.exports = {
  .
  .
  .
  variants: {
    extend: {},
  },
  plugins: [],
+ important: true,
}

こうすることで、className属性に指定したTailwind CSSが既存のスタイルの一部(あるいは全て)を上書きしてくれます。


Material UI便利ですよね。でも、使っているうちに既存のスタイルを少し修正したいときがあります。
例えばAvatarコンポーネントは、画像をいかにもアイコン風な感じに切り取ってくれる点が優秀だと感じていますが、もし既存のサイズより小さくカスタマイズしたい場合次のように書く必要があります。

react.tsx
import {
  Avatar,
  makeStyles,
  createStyles,
  Theme,
} from "@material-ui/core";
react.tsx
const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    small: {
      width: theme.spacing(2), //= '16px'
      height: theme.spacing(2), //= '16px'
    }
  })
);
react.tsx
const classes = useStyles();
return (
  <Avatar className={classes.small}/>
);

Tailwind CSSで書く場合、冒頭の設定を行ったならばこれだけで済みます。

react.tsx
return (
  <Avatar className="w-4 h-4"/> //= 'width: 16px, height: 16px' 
);

なおimportant: trueはTailwind CSSで記述した全てのクラスが!important宣言付きでマークアップされることをtrueにするものですので注意してください。

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