在用 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 条线:
干得漂亮!收工。