CSS 專業技巧收集
一些CSS技巧的收集,能夠幫助你提升專業水平。
1. 使用 :not() 為導航添加/取消邊框
很多人會這樣給導航添加邊框,然后給最后一個取消掉:
/* add border */
.nav li {
border-right: 1px solid #666;
}
/* remove border */
.nav li:last-child {
border-right: none;
} 其實,用CSS的 :not() 可以簡化為下面的代碼:
.nav li:not(:last-child) {
border-right: 1px solid #666;
} 當然,你也可以使用 .nav li + li 甚至 .nav li:first-child ~ li,但是使用 :not() 可以使意圖更加明確。
2. 給 body 添加 line-height 屬性
你不需要為 <p>、<h*> 分別添加 line-height 屬性,相反的,只需要添加到 body 上即可:
body {
line-height: 1;
} 這樣,文本元素就可以很容易的從 body 繼承該屬性。
3. 垂直居中
這并不是什么魔法,你可以垂直居中任何元素:
html, body {
height: 100%;
margin: 0;
}
body {
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;
display: -webkit-flex;
display: flex;
} 還需要其他的?水平居中、垂直居中,在任何時間、任何地方?可以看看CSS-Tricks的這篇文章。
注意:flexbox 在 IE11 下存在一些bug。
4. 使用逗號分割列表
使列表看起來像是用逗號分割的:
ul > li:not(:last-child)::after {
content: ",";
} 通過 :not() 偽類去掉最后一個元素后面的逗號。
5. 使用負的 nth-child 選取元素
使用負的 nth-child 在 1 到 n 之間選擇元素:
li {
display: none;
}
/* 選擇第1到3個元素并顯示它們 */
li:nth-child(-n+3) {
display: block;
} 當然,如果你了解 :not() 的話,還可以這么做:
li:not(:nth-child(-n+3)) {
display: none;
} 是不是非常簡單?
6. 使用 SVG 作 icon 圖標
沒什么理由不使用 SVG 作 icon 圖標:
.logo {
background: url("logo.svg");
} SVG 對于任何分辨率的縮放效果都很好,并且支持 IE9+所有瀏覽器,所以,放棄使用 .png、.jpg、.gif文件吧。
注:以下代碼對于使用輔助設備上網的用戶可以提升可訪問性:
.no-svg .icon-only:after {
content: attr(aria-label);
} 7. 文本展示優化
有時候字體并不是對于所有設備都顯示為最佳效果,所以使用瀏覽器來幫忙吧:
html {
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
} 8. 使用 max-height 實現純CSS幻燈片
使用 max-height 與超出隱藏實現純CSS的幻燈片:
.slider ul {
max-height: 0;
overlow: hidden;
}
.slider:hover ul {
max-height: 1000px;
transition: .3s ease; /* animate to max-height */
} 9. 繼承 box-sizing
讓 box-sizing 繼承自 html :
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
} 這使得在插件或者其他組件中修改 box-sizing 屬性變得更加容易。
10. 設置表格相同寬度
.calendar {
table-layout: fixed;
} 11. 使用 Flexbox 來避免 Margin Hacks
在做多列布局的時候,可以通過 Flexbox 的 space-between 屬性來避免nth-、first-、 last-child 等 hacks:
.list {
display: flex;
justify-content: space-between;
}
.list .person {
flex-basis: 23%;
} 這樣,列之間的空白就會被均勻的填滿。
13. 對空鏈接使用屬性選擇器
當 <a> 中沒有文本而 href 不為空的時候,顯示其鏈接:
a[href^="http"]:empty::before {
content: attr(href);
} 瀏覽器支持
以上技巧支持大部分現代瀏覽器,如:Chrome、Firefox、Safari、Edge以及IE11。