首頁  >  文章  >  web前端  >  CSS進階技巧

CSS進階技巧

高洛峰
高洛峰原創
2016-11-22 10:00:531491瀏覽

使用: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屬性

你不需要為

分別添加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圖標

沒什麼理由不使用SVG作icon圖標:

.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

在做多列布局的时候,可以通过Flexbox的space-between属性来避免nth-、first-、 last-child等hacks:

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

这样,列之间的空白就会被均匀的填满

对空链接使用属性选择器

当3499910bf9dac5ae3c52d5ede7383485中没有文本而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;/*显示多少行文本*/
}


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:CSS語法總結下一篇:CSS語法總結