CSS 樣式技巧
目錄
CSS Sprites(多圖片合併處理)
- 使用工具將多張圖片打包成一張大的 Sprites 圖片,並生成對應的 CSS。
- Gmail 使用此技術:
- 在 Gmail 中,CSS Sprites 技術主要應用於導航圖標、按鈕圖標和功能性小圖標上,比如信件操作區的「刪除」、「標記為已讀」、「標記為垃圾郵件」等圖標,以及收件箱旁邊的「撰寫新郵件」和「篩選」等圖標。這些圖標通常是小且重複使用的圖形,通過使用 CSS Sprites,把它們整合成一張大圖,從而減少加載這些圖標所需的請求數量。
- 每個圖像都有一個對應的 CSS 類,其中定義了
background-image、background-position和background-size屬性。 - 減少多個圖像的 HTTP 請求數量。
- 預先下載直到需要時才會下載的資源,例如僅在
:hover偽狀態時出現的圖像。
樣式化 SVG
- 範例:內建 CSS
<rect x="10" y="10" width="100" height="100" stroke="blue" fill="purple" fill-opacity="0.5" stroke-opacity="0.8" />
- 我有使用 react-native 中的 Art 的經驗,類似,但用法略有不同。
- Art (in react-native):
import React from 'react'; import { View } from 'react-native'; import { Surface, Shape, Path } from 'react-native-art'; const MyArtComponent = () => { const path = new Path() .moveTo(50, 50) .lineTo(100, 100) .lineTo(50, 100) .close(); return ( <View> <Surface width={200} height={200}> <Shape d={path} fill="#FF0000" /> </Surface> </View> ); }; export default MyArtComponent;
字體引入 (Font)
- 使用
@font-face並為不同的font-weight定義font-family。
小程序的上傳流程:
-
上傳字體文件:
- 假設字體文件名為
MyCustomFont.ttf,並上傳到https://example.com/fonts/MyCustomFont.ttf。
- 假設字體文件名為
-
編寫引入代碼: 在
app.wxss文件中添加以下代碼:@font-face { font-family: 'MyCustomFont'; /* 定義字體名稱 */ src: url('https://example.com/fonts/MyCustomFont.ttf') format('truetype'); /* 引入字體文件 */ font-weight: normal; /* 字體重量 */ font-style: normal; /* 字體樣式 */ } -
在頁面或組件中使用字體: 在某個頁面或組件的
.wxss文件中使用該字體,例如在index.wxss文件中:.custom-text { font-family: 'MyCustomFont'; /* 使用自定義字體 */ font-size: 16px; /* 設置字體大小 */ color: #333; /* 設置字體顏色 */ }
CSS 加載動畫
.spinner { width: 50px; /* 設置spinner的大小 */ height: 50px; /* 設置spinner的大小 */ border: 5px solid #ccc; /* 設置邊框顏色 */ border-top: 5px solid #3498db; /* 設置頂部邊框顏色 */ border-radius: 50%; /* 使其成為圓形 */ animation: spin 1s linear infinite; /* 添加旋轉動畫 */ } @keyframes spin { // spin為自定義的,animation中使用 0% { transform: rotate(0deg); /* 從0度開始 */ } 100% { transform: rotate(360deg); /* 旋轉到360度 */ } }
@keyframes:- 定義名為
spin的動畫 - 它指定在 0% 時,spinner 處於 0 度旋轉,而在 100% 時,它已旋轉了完整的 360 度。
- 定義名為
transform:- 在關鍵幀中使用,用於旋轉 spinner
- 將 spinner 的位置從起始角度更改為最終角度,創建旋轉效果。
視覺上隱藏內容
- 寬度、高度等於 0
- position: absolute; left: -999999px; 將內容定位在屏幕外
- Text-indent: -9999px; 可能會引起性能問題
- Text-indent: 100%