快速掌握 Tailwind

113 阅读7分钟

Tailwind 是流行的原子化 css 框架。

创建项目

我们通过 crerate-react-app 创建一个 react 项目,测试tailwind。

npx create-react-app tailwind-test

//然后进入 tailwind-test 目录,执行
npm install -D tailwindcss
npx tailwindcss init

//安装 tailwindcss 依赖,创建 tailwindcss 配置文件。
module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

//tailwind 实际上是一个 postcss 插件,因为 cra 内部已经做了 postcss 集成 tailwind 插件的配置,这一步就不用做了:

//然后在入口 css 里加上这三行代码:App.css
@tailwind base;
@tailwind components;
@tailwind utilities;

//这三行分别是引入 tailwind 的基础样式、组件样式、工具样式的。

//之后就可以在组件里用 tailwind 提供的 class 了:
import './App.css';

function App() {
  return (
    <div className='text-base p-1 border border-black border-solid'>guang</div>
  );
}

export default App;

//我们执行 npm run start 把开发服务跑起来。
npm run start

字符大小设置

要设置字体大小,请使用 text- {size}。大小可以取 13 个值。相应的 CSS 样式在括号中。

.text-xs(字体大小:.75rem;)
.text-sm(字体大小:.875rem;)
.text-base(字体大小:1rem;)
.text-lg(字体大小:1.125rem;)
.text-xl(字体大小:1.25rem;)
.text-2xl(字体大小:1.5rem;)
.text-3xl(字体大小:1.875rem;)
.text-4xl(字体大小:2.25rem;)
.text-5xl(字体大小:3rem;)
.text-6xl(字体大小:4rem;)
.text-7xl(字体大小:4.5rem;)
.text-8xl(字体大小:6rem;)
.text-9xl(字体大小:8rem;)

字符粗细设置

要设置字符粗细,请使用 font- {thickness}。厚度可以取 9 个值。相应的 CSS 样式在括号中。

.font-thin (font-weight: 100;)
.font-extralight (font-weight: 200;)
.font-light (font-weight: 300;)
.font-normal (font-weight: 400;)
.font-medium (font-weight: 500;)
.font-semibold (font-weight: 600;)
.font-bold(font-weight:700;)
.font-extrabold(font-weight:800;)
.font-black(font-weight:900;)

文字颜色设置

要设置文本颜色,请使用 text- {color}-{color depth}。颜色可以设置为白色、黑色、红色、蓝色、靛蓝色……等。颜色强度可以取 「9」 个值。

text-green-100(颜色:# f0fff4;)
text-green-200(颜色:#c6f6d5;)
text-green-300(颜色:#9ae6b4;)
text-green-400(颜色:#68d391;)
text-green-500(颜色:#48bb78;)
text-green-600(颜色:#38a169;)
text-green-700(颜色:#2f855a;)
text-green-800(颜色:#276749;)
text-green-900(颜色:#22543d;)

创建按钮

<button class="bg-indigo-700 font-semibold text-white py-2 px-4 rounded">前端晚间课</button>

//在py-2中,上下设置了.5rem padding,在px-4中,左右设置了1rem padding。在圆形中,边界半径 .25rem 被应用并且角被圆化。

基本元素(均可混着用)

1.高度h-12,宽度w-12,背景色 bg-red-500

2.border你可以设置元素的边框宽度、颜色和样式。

样式:border-solid实线、border-dashed虚线、border-dotted点线

宽度:border-2

颜色:border-red-500

3.inline、inline-block、block

inline元素无法设置宽高,内联元素不会独占一行,它们会在同一行上水平排列;

inline-block可以在一行中放置多个元素,并且它们的宽度和高度可以设置,而不会强制换行。这使得元素既可以享受块级元素的盒模型,又可以在水平方向上保持内联元素的行为;

block这个类通常用于将元素设置为块级元素,使其在文档流中占据整行。

4.invisible、hidden

invisible只是让元素不可见,hidden将元素完全隐藏。

5.flex、justify、items

flex使元素水平排列,flex flex-col使元素竖直排列(规定主轴);

justify总是使元素与flex的方向相同,如:justify-start最前,justify-center居中,justify-end最后,justify-around使首尾元素相距页边相等(是中间各元素间距的一半),且中间各元素之间的间距相同,justify-evenly使各元素及首尾元素距离页边的距离相等;

items的效果取决于交叉轴(垂直主轴)的方向,也有items-center等。

6.h-screen使一个容器占据整个屏幕的高度,无w-screen,有w-full

7.grid grid-cols-6 使元素每行排六个,到六个自动换行

8.边距m-2 填充p-2

边距m(各向)、mt上边距、mr右边距、mb下边距、ml左边距、mx水平方向的边距、my垂直方向的边距;

填充p(各向)、pt上填充、pr右填充、pb下填充、pl左填充、px水平方向的填充、py垂直方向的填充.

9.圆角

rounded-none无圆角、rounded-sm小圆角、rounded中等圆角、rounded-md中等圆角、rounded-lg大圆角、rounded-full完全圆形

10.阴影

shadow-sm: 小型阴影、shadow: 中等阴影、shadow-md: 中等阴影(与 shadow 相同)、shadow-lg: 大型阴影、shadow-xl: 超大型阴影、shadow-2xl: 超超大型阴影、shadow-inner: 内部阴影、shadow-none: 无阴影

效果方法

1.自适应显示

(1)invisible sm:visible md:text-red-500 lg:text-8xl,

(2)flex flex-col text-4xl sm:flex-row,

(3)m-4 rounded-md bg-red-500 px-4 py-2 text-white hover:bg-red-600 active:bg-red-400 sm:bg-indigo-500 sm:hover:bg-indigo-600 sm:active:bg-indigo-400

页面每到一定大小就出现一种效果,hover选中状态,active被激活(点击时),lg、sm都是窗口大小程度(到了就运行效果)

2.聚焦ring-green-500

定义焦点环形边框的颜色和样式。当元素处于聚焦状态时,这个环形边框将显示出来。

ring: 默认的环形边框、ring-inset: 内部环形边框、ring-transparent: 透明环形边框、ring-[color]-[opacity]: 自定义颜色和透明度的环形边框

3.容器包裹下的序号对应效果

被包裹的元素中,first:bg-green-400第一个元素,last:bg-green-400最后一个元素,odd:bg-green-400奇数元素,even:bg-green-400偶数元素;顺序是哪个效果在后方那么满足要求时一律用最后的覆盖前面的

4.group组群

由外层div标识,内层的元素使用group-即可使用外层div的同样效果且可以复写,如:

<div class=”group hover:bg-sky-500”><p class=”group-hover:text-red-500”></div>

5.peer标识

peer是一个类似于JavaScript中相邻选择器的概念。它用于选择同级(同父级)元素中特定状态的元素,而不是嵌套元素。其中被监听的元素一定要写在监听之前,例:

<div>
  <div class=”peer/yellowSquare”></div>
  <div class=”peer/blackSquare”></div>
  <div class=”hidden peer-hover/yellowSquare:block”></div>
  <div class=”hidden peer-hover/blackSquare:block”></div>
</div>

若要排序,使每次显示时在最前面:

<div class=”flex flex-col”>
  <div class=”peer/yellowSquare order-3”></div>
  <div class=”peer/blackSquare order-4”></div>
  <div class=”order-1 hidden peer-hover/yellowSquare:block”></div>
  <div class=”order-2 hidden peer-hover/blackSquare:block”></div>
</div>

自定义主题

bg-[#00d1ad] rounded-[300px] px-[3.2rem]

在tailwindcss.config里添加:

extend:{
  colors:{
    mint:{
      DEFAULT:”#00d1ad”,
      50:”#eefffa”,
      100:”#c6fff0”
    }
  },
  spacing:{
    “128”:”32rem”,
    “144”:”36rem”
  }
  borderRadius:{
    “4xl”:”2rem”
  }
}

引用时:bg-mint bg-mint-50

切换主题

// app.css

@tailwind base;
@tailwind components;
@tailwind utilities;


.App {
  text-align: center;
}

@layer base {
    :root {
        --color-bg-l1: 254, 202, 202;
        --color-bg-l2: 252, 165, 165;
        --color-bg-l3: 248, 113 ,113;
        --color-bg-l4: 239, 68, 68;
    }

    .theme-blue {
        --color-bg-l1: 191, 219, 254;
        --color-bg-l2: 147, 197, 253;
        --color-bg-l3: 96, 165, 250;
        --color-bg-l4: 59, 130, 246;
    }

    .theme-green {
        --color-bg-l1: 187, 247, 208;
        --color-bg-l2: 134, 239, 172;
        --color-bg-l3: 74, 222, 128;
        --color-bg-l4: 34, 197, 94;
    }
}


//tailwind.config.js
/** @type {import('tailwindcss').Config} */
function withOpacity(variableName) {
  return ({opacityValue}) => {
      if (opacityValue != null) {
          return `rgba(var(${variableName}),${opacityValue})`
      }
      return `rgb(var(${variableName})`
  }
}
module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
  theme: {
    colors:{
      mint:{
        DEFAULT:"#00d1ad",
        50:"#eefffa",
        100:"#c6fff0"
      }
    },
    spacing:{
      "128":"32rem",
      "144":"36rem"
    },
    borderRadius:{
      "4xl":"20rem"
    },
    extend: {
      backgroundColor: {
        skin: {
            base: withOpacity(`--color-bg-l1`),
            card: withOpacity(`--color-bg-l2`),
            btn: withOpacity(`--color-bg-l3`),
            'btn-hover': withOpacity(`--color-bg-l4`),
        }
      }
    },
  },
  plugins: [],
}


//app.js
import './App.css';

function App() {
  const themes = ['theme-blue','theme-green']
    const changeTheme = (theme)=>{
        const body = document.body;
        themes.forEach(e=>{
            body.classList.remove(e)
        })
        if (theme) {
          body.classList.add(theme);
        }
    }
  return (
    <div className="App">
      <div className={`transition-all duration-500 bg-skin-base h-screen flex justify-center items-center`}>
            <div className={`transition-all duration-500 bg-skin-card rounded-2xl p-8 min-w-max min-h-max flex flex-col items-center`}>
                <h1 className={`transition-all duration-500 text-amber-50 text-3xl font-extrabold`}>尝试定制你的主题!</h1>
                <h2 className={`transition-all duration-500 text-lg my-3 text-amber-50`}>我们将会使用Tailwindcss和CSS3变量制作主题切换</h2>
                <div className={"transition-all duration-500 w-full flex justify-evenly "}>
                    <input className={`transition-all duration-500 transition-colors cursor-pointer p-2 rounded text-amber-50 opacity-90
                           bg-skin-btn  hover:bg-skin-btn-hover `}
                           type="button"
                           value="红色主题"
                           onClick={()=>changeTheme("")}
                    />
                    <input className={`transition-all duration-500 cursor-pointer p-2 rounded text-amber-50 opacity-90
                           bg-skin-btn  hover:bg-skin-btn-hover `}
                           type="button"
                           value="蓝色主题"
                           onClick={()=>changeTheme(themes[0])}
                    />
                    <input className={`transition-all duration-500 transition-colors cursor-pointer p-2 rounded text-amber-50 opacity-90
                           bg-skin-btn  hover:bg-skin-btn-hover `}
                           type="button"
                           value="绿色主题"
                           onClick={()=>changeTheme(themes[1])}
                    />
                </div>
            </div>
        </div>
    </div>
  );
}

export default App;

源码下载:https://gitee.com/leolee18/tailwind-test