1. 程式人生 > >常用的 CSS 技巧

常用的 CSS 技巧

clas tran borde pos pan 彩色 bili css 用法

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;

}

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 {

  -moz-osx-font-smoothing: grayscale;

  -webkit-font-smoothing: antialiased;

  text-rendering: optimizeLegibility;

}

7.對純 CSS 滑塊使用 max-height

使用 max-height 和溢出隱藏來實現只有CSS的滑塊:

.slider ul {

  max-height: 0;

  overlow: hidden;

}


.slider:hover ul {

  max-height: 1000px;

  transition: .3s ease;

}

8、用 Flexbox 擺脫外邊距的各種 hack

.list {

  display: flex;

  justify-content: space-between;

}


.list .person {

  flex-basis: 23%;

}

當需要用到列分隔符時,通過flexbox的 space-between 屬性,你就可以擺脫nth-,first-,和 last-child 的hack了:

現在,列表分隔符就會在均勻間隔的位置出現。

9、CSS3 calc() 的使用

calc() 用法類似於函數,能夠給元素設置動態的值:

/* basic calc */

.simpleBlock {

  width: calc(100% - 100px);

}


/* calc in calc */

.complexBlock {

  width: calc(100% - 50% / 3);

  padding: 5px calc(3% - 2px);

  margin-left: calc(10% + 10px);

}

9、文本漸變

文本漸變效果很流行,使用 CSS3 能夠很簡單就實現:

h2[data-text] {

  position: relative;

}

h2[data-text]::after {

  content: attr(data-text);

  z-index: 10;

  color: #e3e3e3;

  position: absolute;

  top: 0;

  left: 0;

  -webkit-mask-image: -webkit-gradient(linear, left top, left bottom, from(rgba(0,0,0,0)), color-stop(50%, rgba(0,0,0,1)), to(rgba(0,0,0,0)));}

10、禁用鼠標事件

CSS3 新增的 pointer-events 讓你能夠禁用元素的鼠標事件,例如,一個連接如果設置了下面的樣式就無法點擊了。

.disabled { pointer-events: none; }

常用的 CSS 技巧