提高CSS開發能力的技巧大全

  1 使用:not()給導航條添加間隔線

提高CSS開發能力的技巧大全

我們通常使用如下代碼給導航條增加間隔線

/* add border */

li {

border-right: 1px solid #666;

}

/* remove border */

li:last-child {

border-right: none;

}

現在,我們可以使用:not()選擇符簡化操作,代碼簡潔易讀,不錯吧。

li:not(:last-child) {

border-right: 1px solid #666;

}

或者,我們增加左邊框。

li:first-child ~ li {

border-left: 1px solid #666;

}

  2 給body元素增加Line-Height屬性

我們不需要給每個p、h1元素設置line-height,只需要給body元素設置,其他文本元素會自動繼承body的特性。

body {

line-height: 1;

}

  3 任意元素垂直居中

不是黑魔法,確實可以讓任意元素垂直居中。

html, body {

height: 100%;

margin: 0;

}

body {

-webkit-align-items: center;

-ms-flex-align: center;

align-items: center;

display: -webkit-flex;

display: flex;

}

  4 逗號分隔的.列表

讓html列表貌似現實中逗號分隔的列表

ul > li:not(:last-child)::after {

content: ",";

}

  5 在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;

}

  6 使用svg圖標

沒有理由不使用svg圖標,在大多數分辨率和瀏覽器裏能夠實現縮放,甚至兼容到IE9,所以不用再用.png、.gif等等。

{

background: url("");

}

  7 文本顯示優化

一些字體不能再所有設備中最優展示,所以需要設置。

html {

-moz-osx-font-smoothing: grayscale;

-webkit-font-smoothing: antialiased;

text-rendering: optimizeLegibility;

}

注意optimizeLegibility屬性值的使用問題,同時IE/Edge不支持text-rendering。

  8 在Pure CSS Sliders中使用max-height

使用max-height實現隱藏、顯示的動畫。

er ul {

max-height: 0;

overlow: hidden;

}

er:hover ul {

max-height: 1000px;

transition: .3s ease;

}

參見本博《Auto值的CSS3 Transition解決方案》

  9 初始化box-sizing

從html中繼承box-sizing屬性,這樣的話,後期維護比較方便。

html {

box-sizing: border-box;

}

*, *:before, *:after {

box-sizing: inherit;

}

  10 表格單元格等寬

ndar {

table-layout: fixed;

}

  11 使用Flexbox擺脫各種Margin Hacks

在實現側欄時,我們不再需要各種nth-、first-和last-child等設置margin,可以使用Flexbox輕鬆實現均勻分佈。

{

display: flex;

justify-content: space-between;

}

on {

flex-basis: 23%;

}

  12 給空連接使用屬性選擇符

對於那些擁有href屬性但是內容爲空的a,自動添加內容。

a[href^="http"]:empty::before {

content: attr(href);

}