[CSS] CSS 專家密技精華
以下整理 @sindresorhus 的 Awesome Lists 中我不熟悉的觀念:
詳細內容可參考連結。
1.使用 unset 而不是重置所有屬性
當重置元素的屬性時,並不需要重置元素中每個屬性:
button {
background: none;
border: none;
color: inherit;
font: inherit;
outline: none;
padding: 0;
}
你可以用 all 來代表元素中所有的樣式屬性。 將該值設定為 unset 意味著將元素中所有樣式屬性回復到預設值:
button {
all: unset;
}
2.檢查字體是否在本地安装
@font-face {
font-family: "Dank Mono";
src:
/* Full name */
local("Dank Mono"),
/* Postscript name */
local("Dank Mono"),
/* Otherwise, download it! */
url("//...a.server/fonts/DankMono.woff");
}
code {
font-family: "Dank Mono", system-ui-monospace;
}
3.使用負數的 nth-child 來選擇元素
li {
display: none;
}
/* 選擇第 1 至第 3 個元素並顯示出來 */
li:nth-child(-n+3) {
display: block;
}
4.使用 SVG 圖示
SVG 在所有解析度下都可以良好縮放,並且支援 IE9 之後的所有瀏覽器,丟棄你的 .png, .jpg, 或 .gif 檔案!
5.讓表格中每個儲存格維持等寬
.calendar {
table-layout: fixed;
}
6.利用屬性選擇器填滿空白連結的文字內容
a[href^='http']:empty::before {
content: attr(href);
}
7.幫沒有類別的連結設定一個預設樣式
a[href]:not([class]) {
color: #008000;
text-decoration: underline;
}
- 為破圖定義樣式
只要一點 CSS 就可以美化所有破圖:
img {
display: block;
font-family: sans-serif;
font-weight: 300;
height: auto;
line-height: 2;
position: relative;
text-align: center;
width: 100%;
}
接著新增一個 偽元素規則 (pseudo-elements rules) 來顯示使用者訊息,以及這張破圖的 URL 參考:
img::before {
content: "We're sorry, the image below is broken :(";
display: block;
margin-bottom: 10px;
}
img::after {
content: '(url: ' attr(src) ')';
display: block;
font-size: 12px;
}
9.用 rem 來調整全域大小;用 em 來調整區域大小
在根元素設定基礎字體大小後 (html { font-size: 100%; }),
使用 em 設定文字元素的字體大小:
h2 {
font-size: 2em;
}
p {
font-size: 1em;
}
然後設定模組的字體大小為 rem:
article {
font-size: 1.25rem;
}
aside .module {
font-size: 0.9rem;
}
10.使用 :root 選擇器來設定彈性的字體大小
在響應式版面(responsive layout)中,字體大小通常需要根據不同的 Viewport (畫面大小) 進行調整。你可以根據 :root 所定義的 Viewport 高度與寬度來調整字體大小:
:root {
font-size: calc(1vw + 1vh + 0.5vmin);
}
現在你便能使用依 :root 字級為基準的 rem 單位了。
body {
font: 1rem/1.6 sans-serif;
}
資源整理:
垂直、水平置中大整理
https://css-tricks.com/centering-css-complete-guide/