在用 CSS 進行繪圖和佈局時,除了藉助瀏覽器開發工具以外,還常常須要繪製一些輔助線,以便定位參考。今天就以第 170 號做品中使用的網格線爲例,詳細講解一下輔助線的原理和畫法。php
爲了使輔助線明顯可見,把線的顏色設置爲和背景對比強烈的白色,而且線也粗一些,在實際使用時,你應該下降輔助線與背景的對比而且使用細線。css
div { font-size: 50px; width: 6em; height: 4em; background-color: teal; }
假設你有一個 <div>
容器,容器裏是否有元素均可以,當前演示爲了突顯輔助線,暫時讓容器裏空空如也:segmentfault
div { background-image: linear-gradient(to bottom, transparent 95%, white 95%); }
網格線是一條一條線條組成的,因此要先畫出一條線,它的95%都是透明的,只有5%是白色的:瀏覽器
div { background-size: 1em 1em; background-repeat: no-repeat; }
請把繪製網格線想象成是鋪地磚,首先要定義地磚的尺寸,這裏用 1em 1em
定義了一塊方磚,同時讓磚塊不重複,因此只顯示出了孤單的一塊磚:函數
div { background-repeat: repeat-x; }
若是把地磚橫向平鋪,就能組合成一條水平線:工具
div { background-repeat: repeat-y; }
若是把地磚縱向平鋪,就能組合成一條垂直線。
錯!
縱向平鋪是像階梯同樣的效果:佈局
div { background-repeat: repeat; }
橫向和縱向同時平鋪,就是像做業本同樣的多條橫線效果。注意,這時最頂端是沒有線的:開發工具
div { background-image: linear-gradient(to right, transparent 95%, white 95%); background-size: 1em 1em; background-repeat: repeat; }
假如把地磚換成向右的豎線,即只把 to bottom
改成 to right
,其餘不變,繪製出的就是一排一排的豎線。一樣注意,這時最左邊是沒有線的:spa
div { background-image: linear-gradient(to bottom, transparent 95%, white 95%), linear-gradient(to right, transparent 95%, white 95%); background-size: 1em 1em; background-repeat: repeat; }
把第6步和第7步合併起來,網格線基本成型了,不過頂端和左端還缺乏線條:code
div { background-image: linear-gradient(to top, transparent 95%, white 95%); background-size: 1em 1em; background-repeat: no-repeat; }
來解決頂端線的問題,先畫出一段頂端線。這段代碼和第3步極類似,僅僅是 to bottom
改爲了 to top
:
div { background-repeat: repeat-x; }
把這一段頂端線水平平鋪,就是一條定位在頂部的水平線:
div { background-image: linear-gradient(to left, transparent 95%, white 95%); background-size: 1em 1em; background-repeat: no-repeat; }
用相似的辦法解決左端線問題,先定義一段左端線,注意 linear-gradient
函數的第 1 個參數改爲 to left
了:
div { background-repeat: repeat-y; }
平鋪這段左端線,就獲得了一條緊挨容器左側的豎線:
div:nth-child(13) { background-image: linear-gradient(to bottom, transparent 95%, white 95%), linear-gradient(to right, transparent 95%, white 95%), linear-gradient(to top, transparent 95%, w hite 95%), linear-gradient(to left, transparent 95%, white 95%); background-size: 1em 1em; background-repeat: repeat, repeat, repeat-x, repeat-y;
好了,咱們把第8步不完美的網格線、頂端線、左端線都合起來,就是完美的網格線了,注意 background-repeart
的寫法,它有 4 個參數,分別對應 background-image
裏的 4 條線:
幹得漂亮!收工。