CSS 進階技巧匯總,css技巧匯總

來源:互聯網
上載者:User

CSS 進階技巧匯總,css技巧匯總

在我們平時寫代碼的時候沒有沒有掌握一些CSS技巧呢? 今天給大家分享一個《CSS 進階技巧匯總讓你的代碼簡潔高效》。大家務必掌握這些小技巧,會讓你非常高效率的寫出網頁的。

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

 

◆給 body添加行高

你不需要分別添加 line-height 到每個 <p>,<h*>等。只要添加到 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;}

看,是不是很簡單。

註:在IE11中要小心flexbox。

◆逗號分隔的列表

讓HTML清單項目看上去像一個真正的,用逗號分隔的列表:

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:

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

 

SVG對所有的解析度類型都具有良好的擴充性,並支援所有瀏覽器都迴歸到IE9。這樣可以避開.png、.jpg或.gif檔案了。

◆最佳化顯示文本

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

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

 

相當方便。

◆支援這些進階技巧在Chrome、Firefox、Safari、Edge的目前的版本,以及IE11中都能有效工作。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.