經常使用的20個css高階技巧(上)
阿新 • • 發佈:2019-01-29
1. 黑白影象
這段程式碼會讓你的彩色照片顯示黑白照片。
img.desaturate {
filter: grayscale(100%);
-webkit-filter: grayscale(100%);
-moz-filter: grayscale(100%);
-ms-filter: grayscale(100%);
-o-filter: grayscale(100%);
}
2. 使用 :not() 在選單上應用/取消應用邊框
首先 給每一個選單項新增邊框:
/* add border */
.nav li {
border-right: 1px solid #666 ;
}
再除去最後一個元素
// remove border /
.nav li:last-child {
border-right: none;
}
可以直接使用 :not() 偽類來應用元素:
.nav li:not(:last-child) {
border-right: 1px solid #666;
}
最簡便的:如果你的新元素有兄弟元素的話,也可以使用通用的兄弟選擇符(~)
..nav li:first-child ~ li {
border-left: 1px solid #666;
}
3. 頁面頂部陰影
簡單的 CSS3 程式碼片段可以給網頁加上漂亮的頂部陰影效果:
body:before {
content: "";
position: fixed;
top: -10px;
left: 0;
width: 100%;
height: 10px;
-webkit-box-shadow: 0px 0px 10px rgba(0,0,0,.8);
-moz-box-shadow: 0px 0px 10px rgba(0,0,0,.8);
box-shadow: 0px 0px 10px rgba(0,0,0,.8);
z-index : 100;
}
4. 給 body 新增行高
你不需要分別新增 line-height 到每個p,h標記等。只要新增到 body 即可:
body {
line-height: 1;
}
這樣文字元素就可以很容易地從 body 繼承。
5. 所有一切都垂直居中
要將所有元素垂直居中,太簡單了:
html, body {
height: 100%;
margin: 0;
}
body {
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;
display: -webkit-flex;
display: flex;
}
注意:在IE11中要小心flexbox。
6. 逗號分隔的列表
讓HTML列表項看上去像一個真正的,用逗號分隔的列表:
ul > li:not(:last-child)::after {
content: ",";
}
對最後一個列表項使用 :not() 偽類。
7. 使用負的 nth-child 選擇專案
在CSS中使用負的 nth-child 選擇專案1到專案n。
li {
display: none;
}
/* select items 1 through 3 and display them */
li:nth-child(-n+3) {
display: block;
}
8. 對圖示使用 SVG
我們沒有理由不對圖示使用SVG:
.logo {
background: url("logo.svg");
}
9. 優化顯示文字
有時,字型並不能在所有裝置上都達到最佳的顯示,所以可以讓裝置瀏覽器來幫助你:
html {
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
}
注:請負責任地使用 optimizeLegibility。此外,IE /Edge沒有 text-rendering 支援。
10. 對純 CSS 滑塊使用 max-height
使用 max-height 和溢位隱藏來實現只有CSS的滑塊:
.slider ul {
max-height: 0;
overlow: hidden;
}
.slider:hover ul {
max-height: 1000px;
transition: .3s ease;
}