原文作者:knaagar
原文連結:https://dev.to/devsyedmohsin/css-tips-and-tricks-you-will-add-to-cart-163p
翻譯:沙漠盡頭的狼
既然我們已經完成了 HTML 和 JavaScript 技巧,現在是時候介紹 CSS 技巧與訣竅了 💖✨
1. 列印媒體查詢
您可以使用列印媒體查詢為網站的列印版本設定樣式。
@media print {
* {
background-color: transparent;
color: #000;
box-shadow: none;
text-shadow: none;
}
}
2. 漸層文字
h1 {
background-image: linear-gradient(to right, #c6ffdd, #fbd786, #f7797d);
background-clip: text;
-webkit-background-clip: text;
color: transparent;
}

3. 修改媒體預設值
撰寫 CSS 重置時,加入這些屬性以改善媒體預設值。
img,
picture,
video,
svg {
max-width: 100%;
object-fit: contain; /* 維持良好的比例 */
}
4. 欄數 (column count)
使用欄位屬性為文字元素製作漂亮的欄位佈局。
p {
column-count: 3;
column-gap: 5rem;
column-rule: 1px solid salmon; /* 欄位之間的邊框 */
}

5. 使用 position 居中元素
div {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
6. 逗號分隔的清單
li:not(:last-child)::after {
content: ",";
}

7. 平滑捲動
html {
scroll-behavior: smooth;
}

8. hyphens
hyphens 告知瀏覽器在換行時如何使用連字符連接單詞。可以完全阻止使用連字符,也可以控制瀏覽器什麼時候使用,或者讓瀏覽器決定什麼時候使用。

9. first letter
避免不必要的 span,並使用偽元素來設計你的內容,同樣第一個字母的偽元素,我們還有第一行的偽元素。
h1::first-letter {
color: #ff8a00;
}

10. accent-color
accent-color 屬性能夠使用自訂顏色值重新著色瀏覽器預設樣式提供的表單控制項的強調顏色。

11. 圖片填充文字
h1 {
background-image: url("illustration.webp");
background-clip: text;
color: transparent;
}

12. placeholder 偽元素
使用 placeholder 偽元素來改變 placeholder 樣式:
input::placeholder {
font-size: 1.5em;
letter-spacing: 2px;
color: green;
text-shadow: 1px 1px 1px black;
}

13. 顏色動畫
使用顏色旋轉濾鏡改變元素顏色。
button {
animation: colors 1s linear infinite;
}
@keyframes colors {
0% {
filter: hue-rotate(0deg);
}
100% {
filter: hue-rotate(360deg);
}
}

14. 使用 margin 居中
.parent {
display: flex; /* display: grid; 也有效 */
}
.child {
margin: auto;
}
15. clamp() 函式
clamp() 函式的作用是把一個值限制在一個上限和下限之間,當這個值超過最小值和最大值的範圍時,在最小值和最大值之間選擇一個值使用。它接收三個參數:最小值、首選值、最大值。
h1 {
font-size: clamp(5.25rem, 8vw, 8rem);
}

16. selection 偽類
設定選中元素的樣式。
::selection {
color: coral;
}

17. decimal leading zero
將清單樣式類型設定為十進位前導零。
li {
list-style-type: decimal-leading-zero;
}

18. 使用 Flex 居中
.parent {
display: flex;
justify-content: center;
align-items: center;
}
19. 自訂游標
html {
cursor: url("no.png"), auto;
}

20. caret-color
caret-color 屬性用來定義插入游標(caret)的顏色,這裡說的插入游標,就是那個在網頁的可編輯器區域內,用來指示使用者的輸入具體會插入到哪裡的、一閃一閃形似豎槓 | 的東西。

22. resize 屬性
將 resize 屬性設定為 none 以避免調整 textarea 的大小
textarea {
resize: none;
}
23. only-child
CSS 偽類 :only-child 匹配沒有任何兄弟元素的元素。等效的選擇器還可以寫成 :first-child:last-child 或者 :nth-child(1):nth-last-child(1),當然,前者的權重會低一點。

24. 使用 grid 居中元素
.parent {
display: grid;
place-items: center;
}
25. text-indent
text-indent 屬性定義一個塊元素首行文字內容之前的縮排量。
p {
text-indent: 5.275rem;
}

26. list style type
CSS 屬性 list-style-type 可以設定列表元素的 marker(像是圓點、符號、或者自訂計數器樣式)。
li {
list-style-type: "🟧";
}
