12個CSS高級技巧彙總

使用 :not() 在菜單上應用/取消應用邊框      先給每個菜單項添加邊框html

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

     ……而後再除去最後一個元素……   web

  // remove border /
  
  .nav li:last-child {
  
  border-right: none;}

     ……能夠直接使用 :not() 僞類來應用元素:   瀏覽器

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

     這樣代碼就乾淨,易讀,易於理解了。      固然,若是你的新元素有兄弟元素的話,也可使用通用的兄弟選擇符(~):   ide

  .nav li:first-child ~ li {
  
  border-left: 1px solid #666;}

     給 body添加行高      你不須要分別添加 line-height 到每一個 <p>,<h*>等。只要添加到 body 便可:   svg

  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;}

     看,是否是很簡單。      注:在IE11中要當心flexbox。      逗號分隔的列表      讓HTML列表項看上去像一個真正的,用逗號分隔的列表:   flex

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

     對最後一個列表項使用 :not() 僞類。      使用負的 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;}

     就是這麼容易。      對圖標使用SVG      咱們沒有理由不對圖標使用SVG:   flexbox

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

     SVG對全部的分辨率類型都具備良好的擴展性,並支持全部瀏覽器都回歸到IE9。這樣能夠避開.png、.jpg或.gif文件了。      優化顯示文本      有時,字體並不能在全部設備上都達到最佳的顯示,因此可讓設備瀏覽器來幫助你:   url

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

    }

     注:請負責任地使用 optimizeLegibility。此外,IE /Edge沒有 text-rendering 支持。      對純CSS滑塊使用 max-height      使用 max-height 和溢出隱藏來實現只有CSS的滑塊:   

.slider ul {max-height: 0;overlow: hidden;}
    .slider:hover ul {max-height: 1000px;transition: .3s ease;}

     繼承 box-sizing      讓 box-sizing 繼承 html:   

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

     這樣在插件或槓桿其餘行爲的其餘組件中就能更容易地改變 box-sizing 了。      表格單元格等寬      表格工做起來很麻煩,因此務必儘可能使用 table-layout: fixed 來保持單元格的等寬:   

  .calendar {table-layout: fixed;}

     用Flexbox擺脫外邊距的各類hack      當須要用到列分隔符時,經過flexbox的 space-between 屬性,你就能夠擺脫nth-,first-,和 last-child 的hack了:   

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

     如今,列表分隔符就會在均勻間隔的位置出現。      使用屬性選擇器用於空連接      當 <a> 元素沒有文本值,但 href 屬性有連接的時候顯示連接:   

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

     至關方便。

相關文章
相關標籤/搜索