九.使用子選擇器(descendantselectors)
CSS初學者不知道使用子選擇器是影響他們效率的原因之一。子選擇器可以幫助你節約大量的class定義。我們來看下面這段代碼:
- <dividdivid=subnav>
- <ul>
- <liclassliclass=subnavitem><ahrefahref=#class=subnavitem>Item1< span>a>< span>li>>
- <liclassliclass=subnavitemselected>
- <ahrefahref=#class=subnavitemselected>Item1< span>a>< span>li>
- <liclassliclass=subnavitem><ahrefahref=#class=subnavitem>Item1< span>a>< span>li>
- < span>ul>
- < span>div>
這段代碼的CSS定義是:
- div#subnavul{/*Somestyling*/}
- div#subnavulli.subnavitem{/*Somestyling*/}
- div#subnavulli.subnavitema.subnavitem{/*Somestyling*/}
- div#subnavulli.subnavitemselected{/*Somestyling*/}
- div#subnavulli.subnavitemselecteda.subnavitemselected{/*Somestyling*/}
你可以用下面的方法替代上面的代碼
- <ulidulid=subnav>
- <li><ahrefahref=#>Item1< span>a>< span>li>
- <liclassliclass=sel><ahrefahref=#>Item1< span>a>< span>li>
- <li><ahrefahref=#>Item1< span>a>< span>li>
- < span>ul>
樣式定義是:
- #subnav{/*Somestyling*/}
- #subnavli{/*Somestyling*/}
- #subnava{/*Somestyling*/}
- #subnav.sel{/*Somestyling*/}
- #subnav.sela{/*Somestyling*/}
用子選擇器可以使你的代碼和CSS更加簡潔、更加容易閱讀。
【編輯推薦】