CSS減少代碼重復技巧非常多,以主要包含采用相對尺寸、半透明顏色的實例來說明CSS減少代碼重復技巧的一些運用。
以下為通過CSS代碼實現的一個“Yes!”按鈕效果以及相應的代碼:
<span class='basisButton'> Yes! </span>
與之組合的CSS代碼:
.basisButton { padding: 6px 16px; border: 1px solid #446d88; background: #58a linear-gradient(#77a0bb, #58a); border-radius: 4px; box-shadow: 0 1px 5px gray; color: white; text-shadow: 0 -1px 1px #335166; font-size: 20px; line-height: 30px; }
#相對尺寸的使用
行高是字號的1.5倍,可以修改為:
font-size: 20px; line-height: 1.5em;
字號也可以根據父元素字號修改為相對尺寸:
font-size: 1.25em; /* 假設父級元素字號為16px*/ line-height: 1.5em;
將padding、border-radius、box-shadow以及text-shadow值也根據字號為基准修改為相對尺寸:
.basisButton { padding: .3em .8em; border: 1px solid #446d88; background: #58a linear-gradient(#77a0bb, #58a); border-radius: .2em; box-shadow: 0 .05em .25em gray; color: white; text-shadow: 0 -.05em .05em #335166; font-size: 125%; line-height: 1.5; }
此處邊框寬度並未修改,是因為放大后,按鈕的邊框粗細不隨着放大保持在1px效果較好。
#半透明顏色的使用
顏色是另一個重要的變數。比如,假設我們要創建一個紅色的取消按鈕,或者一個綠色的確定按鈕,該怎么做呢?眼下,我們可能需要覆蓋四條聲明(border-color、background、box-shadow 和 text-shadow),而且還有另一大難題:要根據按鈕的亮面和暗面相對於主色調 #58a 變亮和變暗的程度來分別推導出其他顏色各自的亮色和暗色版本。此外,若我們想把按鈕放在一個非白色的背景之上呢?顯然使用灰色( gray)作投影只適用於純白背景的情況。其實只要把半透明的黑色或白色疊加在主色調上,即可產生主色調的亮色和暗色變體,這樣就能簡單地化解這個難題了:
.basisButton { padding: .3em .8em; border: 1px solid rgba(0, 0, 0, .1); background: #58a linear-gradient(hsla(0, 0%, 100%, .2), transparent); border-radius: .2em; box-shadow: 0 .05em .25em rgba(0, 0, 0, .5); color: white; text-shadow: 0 -.05em .05em rgba(0, 0, 0, .5); font-size: 125%; line-height: 1.5; }
如果想要覆蓋掉background-color屬性,就可以得到不同眼的版本按鈕。
<span class='basisButton red'> Yes! </span>
.red{ background-color:#c00; }