CSS高階技巧

luckyw發表於2016-11-20

使用:not()在選單上新增/取消邊框


很多人會這樣給導航新增邊框,然後給最後一個取消掉:

/* add border */
.nav li {
  border-right: 1px solid #666;
}
/* remove border */
.nav li:last-child {
  border-right: none;
}

其實,用CSS3:not()可以簡化為下面的程式碼:

.nav li:not(:last-child) {
  border-right: 1px solid #666;
}

當然,你也可以使用.nav li + li甚至.nav li:first-child ~ li,但是使用:not()可以使意圖更加明確
所有主流瀏覽器均支援:not選擇器,除了IE8及更早的版本

body新增line-height屬性


你不需要為<p><h*>分別新增line-height屬性,相反的,只需要新增到body上即可:

body {
  line-height: 1;
}

這樣,文字元素就可以很容易的從body繼承該屬性

垂直居中


可以垂直居中任何元素:

html, body {
  height: 100%;
  margin: 0;
}
body {
  -webkit-align-items: center;
  -ms-flex-align: center;
  align-items: center;
  display: -webkit-flex;
  display: flex;
}

注:flexbox在IE11下存在一些bug

使用逗號分割列表


使列表看起來像是用逗號分割的:

ul > li:not(:last-child)::after {
  content: ",";
}

通過:not()偽類去掉最後一個元素後面的逗號

使用負的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;
}

使用SVG作icon圖示


沒什麼理由不使用SVGicon圖示:

.logo {
  background: url("logo.svg");
}

SVG對於任何解析度的縮放效果都很好,並且支援 IE9+所有瀏覽器,所以,放棄使用png、jpg、gif檔案吧
注:以下程式碼對於使用輔助裝置上網的使用者可以提升可訪問性:

.no-svg .icon-only:after {
  content: attr(aria-label);
}

優化顯示文字


有時,字型並不能在所有裝置上都達到最佳的顯示,所以可以讓裝置瀏覽器來幫助你:

html {
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
  text-rendering: optimizeLegibility;
}

注:請負責任地使用optimizeLegibility。此外IE/Edge不支援text-rendering

使用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 */
}

繼承box-sizing


box-sizing繼承自html

html {
  box-sizing: border-box;
}
*, *:before, *:after {
  box-sizing: inherit;
}

這使得在外掛或者其他元件中修改box-sizing屬性變得更加容易

設定表格相同寬度


.calendar {
  table-layout: fixed;
}

使用Flexbox來避免Margin Hacks


在做多列布局的時候,可以通過Flexboxspace-between屬性來避免nth-first-last-child等hacks:

.list {
  display: flex;
  justify-content: space-between;
}
.list .person {
  flex-basis: 23%;
}

這樣,列之間的空白就會被均勻的填滿

對空連結使用屬性選擇器


<a>中沒有文字而href不為空的時候,顯示其連結:

a[href^="http"]:empty::before {
  content: attr(href);
}

文字溢位省略的處理方法

單行文字溢位

.inline{
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

多行文字溢位

.foo{
    display: -webkit-box!important;
    overflow: hidden;
    text-overflow: ellipsis;
    word-break: break-all;
    -webkit-box-orient: vertical;/*方向*/
    -webkit-line-clamp:4;/*顯示多少行文字*/
}

相關文章