2、css效能最佳化專題————呱呱二號,css效能最佳化
css選取器最佳化
首先,css選取器的解析順序是由右到左的
for example:
1.(1)box > span
瀏覽器渲染網頁的時候是先搜尋span,接著一直向上搜尋,直到搜尋到span的父級元素為.box,如果搜尋不到,就會尋找下一個span。
1.(2).box span
瀏覽器渲染網頁的時候是先搜尋span,接著一直向上搜尋,直到搜尋到span的父輩元素為.box,如果搜尋不到,就會尋找下一個span。
相比之下,1.(1)的效率會比1.(2)的效率要高。
2.(1)#btn
在一個頁面上每一個id都是唯一的,瀏覽器會直接尋找到#btn的元素,並進行渲染。
2.(2)button#btn
這個例子相對於上面的選取器多了一個button,瀏覽器尋找到#btn的元素之後,還會再尋找button元素。
3.[name="submit"]
盡量不要使用全域選取器
4.多個規則還不如直接使用一個特殊的class
for example:
4.(1)div .box ul li a
4.(2).div-a
5.巧用css繼承屬性,減少代碼使用。
不可繼承的:display、margin、border、padding、background、height、min-height、max-height、width、min-width、max-width、overflow、position、left、right、top、bottom、z-index、float、clear、table-layout、vertical-align、page-break-after、page-bread-before和unicode-bidi。所有元素可繼承:visibility和cursor。內嵌元素可繼承:letter-spacing、word-spacing、white-space、line-height、color、font、font-family、font-size、font-style、font-variant、font-weight、text-decoration、text-transform、direction。終端塊狀元素可繼承:text-indent和text-align。列表元素可繼承:list-style、list-style-type、list-style-position、list-style-image。表格元素可繼承:border-collapse。 font屬性書寫格式(僅css1)
font : font-style font-variant font-weight font-size line-height font-family;
font屬性預設值
font: normal normal normal medium normal "Times New Roman" ; 5.css放在head位置css放在head位置的好處就是,在載入css檔案的時候,瀏覽器不會渲染頁面,只有css檔案載入好了之後才會進行渲染頁面。而在此之前,頁面都以空白顯示。 6.css縮寫,可以減少代碼的使用,以達到檔案更小的目的。