版本:VUE3 + TS 框架 vite
文章中使用tailwindcss 版本: ^3.4.17
簡介: Tailwind CSS 一個CSS 框架,提供組件化的樣式,直接在HTML 中編寫樣式,無需額外自定義CSS ,快速! 簡潔!復用!不擔心命名困擾!在使用中,會自動刪除未使用樣式,減輕項目體積。
官網:Tailwind CSS - 只需書寫 HTML 代碼,無需書寫 CSS,即可快速構建美觀的網站。 | TailwindCSS中文文檔 | TailwindCSS中文網
一、安裝并使用
①安裝 tailwindcss
npm install -D tailwindcss@3.4.17 postcss autoprefixer // 安裝 Tailwind CSS 以及相關依賴,保證完整功能
或
yarn add -D tailwindcss@3.4.17 postcss autoprefixer
②創建 postcss.config.ts 和 tailwind.config.ts
在項目根目錄即 src 文件夾同級目錄,內容配置如下:
postcss.config.ts 配置如下
export default{plugins: {tailwindcss: {},autoprefixer: {},},
}// 如果是 js 項目則只需要修改為
module.exports ={plugins: {tailwindcss: {},autoprefixer: {},},
}
tailwind.config.ts
export default{content: ["./index.html","./src/**/*.{vue,js,ts,jsx,tsx}",],theme: {extend: {},},plugins: []
}// 如果是 js 項目則只需要修改為
module.exports ={content: ["./index.html","./src/**/*.{vue,js,ts,jsx,tsx}",],theme: {extend: {},},plugins: []
}
③加載 tailwind? 指令
在項目的主 CSS 文件(全局css樣式文件)中添加以下內容
@tailwind base;
@tailwind components;
@tailwind utilities;
?然后在你的?vite.config.ts 中完成以下配置
向css 的postcss的plugins 添加?tailwindcss 和 autoprefixer
import tailwindcss from "tailwindcss";
import autoprefixer from "autoprefixer";export default defineConfig({...css: {postcss: {plugins: [tailwindcss, autoprefixer,],},},})
④開始使用
tailwindcss:官網 Tailwind CSS - 只需書寫 HTML 代碼,無需書寫 CSS,即可快速構建美觀的網站。 | TailwindCSS中文文檔 | TailwindCSS中文網
進入官網查看樣式寫法
?使用案例如下:
// 字體大小 16px 顏色 #000 懸浮顏色 red 內容居中 懸浮時鼠標為可點擊狀態
<div class="text-[16px] text-[#000] hover:text-[red] text-center cursor-pointer">文字字體設置
</div>
// 寬 150px 高50px 背景顏色 #000 且透明0.4
<div class="w-[150px] h-[50px] bg-[#000]/40"></div>
二、優點詳解
①快速簡潔
// 快速布局 透明顏色 圓角 hover 樣式 文字超出優化<div class="p-[48px] bg-[#f9f9f9] flex items-center flex-wrap"><!-- flex 布局 --><div class="w-[350px] h-[300px] p-[12px] flex justify-between items-center flex-wrap border-[1px]"><div v-for="i in 4" class="bg-[red] w-[120px] h-[120px]"></div></div><div class="w-[400px] h-[280px] bg-[#000]/10 ml-[12px]"></div> <div class="w-[280px] h-[280px] bg-[#000]/10 ml-[12px] rounded-[100%]"></div><div class="w-[280px] h-[280px] bg-[#000]/10 ml-[12px] rounded-[100%] hover:bg-[red]/10"></div><div class="w-[200px] overflow-hidden whitespace-nowrap text-ellipsis p-[12px]">文字超出優化文字超出優化文字超出優化文字超出優化</div></div>
?效果圖:
②組件化 復用
對于常用的 CSS 樣式寫了之后,后面之后復制粘貼 HTML 標簽即可,無需在引入 style
例如 遮罩層樣式:
<!-- 外部盒子 --><div class="w-[350px] h-[350px]"><!-- 圖片遮罩層 --><div class="relative w-full h-full hover cursor-pointer"><imgsrc="https://picsum.photos/200/300"class="w-full h-full object-cover"/><divclass="w-full h-full absolute bg-[#000] top-0 opacity-0 hover:opacity-80 flex justify-center items-center"><p class="text-[18px] text-[#409EFF] font-semibold">查看詳情</p></div></div></div>
效果如下:
樣式定義完成之后,后面使用時,直接可進行復用
總結:使用 tailwindcss 可進行樣式組件化,直接在HTML 中編寫樣式,無需額外自定義CSS 可以快速簡潔的完成頁面的樣式構造 ,且不用考慮類名重復問題,支持 過渡 ?懸浮 透明 flex 布局 排版等樣式排版功能,完善切強大,省去了傳統 CSS 的選擇器嵌套、樣式覆蓋、BEM 命名等繁瑣的步驟,針對日常開發需求可減少大量編寫css樣式的時間,提高開發效率。