Sticky Note | React 中 CSS 的一些 Lib 方案

465 阅读1分钟

e.g. React + Vite

tailwind

tailwindcss.com/docs/guides…

  1. install dependencies
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
  1. configure tailwindcss.config.cjs
/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'],
  theme: {
    extend: {},
  },
  plugins: [],
};
  1. add the Tailwind directives to your CSS
@tailwind base;
@tailwind components;
@tailwind utilities;
  1. write tailwind anywhere
const App = () => {
  return (
    <div className="flex items-center justify-center h-screen">
      <h1 className="text-5xl font-bold underline italic">Hello Tailwind CSS !</h1>
    </div>
  );
};

export default App;

@emotion/css

emotion.sh/docs/introd…

import { css } from '@emotion/css';

// 标签字符串写法和css中写法一致 但是没有语法提示
const wrapperStyles = css`
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
`;

// 对象写法 用驼峰写法 有语法提示
const textStyled = css({
  fontSize: '3rem',
  lineHeight: 1,
  textDecorationLine: 'underline',
  fontStyle: 'initial',
});

const App = () => {
  return (
    <div className={wrapperStyles}>
      <h1 className={textStyled}>Hello @emotion/css !</h1>
    </div>
  );
};

export default App;

styled-components

styled-components.com/

这个写法和 emotion 的几乎一致

区别是 styled-component 是创建一个包含样式的组件 而 emotion 是直接创建样式

import styled from 'styled-components';

// 标签字符串写法 和css中写法一致 但是没有语法提示
const Wrapper = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
`;

// 对象写法 用驼峰写法 有语法提示
const Text = styled.h1({
  fontSize: '3rem',
  lineHeight: 1,
  textDecorationLine: 'underline',
  fontStyle: 'initial',
});

const App = () => {
  return (
    <Wrapper>
      <Text>Hello Styled Components !</Text>
    </Wrapper>
  );
};

export default App;

jss

github.com/cssinjs/jss

styled-jsx

www.npmjs.com/package/sty…

css-modules

将 css 文件后缀改成 xxx.module.css 即可

下面是一个简单的例子

/* App.module.css */
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

.text {
  font-size: 3rem;
  line-height: 1;
  text-decoration-line: underline;
  font-style: italic;
}
import styles from './App.module.css';

const App = () => {
  return (
    <div className={styles.wrapper}>
      <h1 className={styles.text}>Hello CSS Modules !</h1>
    </div>
  );
};

export default App;