如何用css3实现半像素边框

来源:互联网 发布:php代替session 编辑:程序博客网 时间:2024/05/16 17:43

今天小编遇到一个头疼的问题,如何实现一个半(0.5)像素的边框

像一个像素的边框,我们很容易解决,直接一个border:1px solid red;就很容易实现了

那么我们直接一个border:0.5px solid red;不就解决实现0.5像素的边框问题了吗?

答案是不行的,因为border的with只能是自然数


所以我们要运用到CSS3中伪类元素来解决这一问题


思路:

1.设置目标元素作为定位参照

.connet{position: relative;  width: 100px;height: 100px;}

2.给目标元素添加一个伪类元素before或者after,并设置为绝对定位

.connet:after{   content: '';position: absolute;  }

3.为伪类元素添加1px的边框

.connet:after{   border: 1px solid red;}

4.设置伪类元素的宽高为目标元素的2倍

.connet:after{  width: 200%;height: 200%;}

5.将伪类元素缩小0.5倍(变回目标元素的大小)

.connet:after{   transform-origin:0 0;   transform: scale(0.5,0.5);}


6.把border包进来(意思就是先放大再缩回来,border-box是关键,否则边框不会一起缩放)

.connet:after{   box-sizing:border-box;}

其具体代码为

<!DOCTYPE html><html><head><meta charset="utf-8" /><title></title></head><style type="text/css">#box{   /*此元素作为参照比较*/width: 150px;height: 150px;border: 1px solid red;padding: 10px;}.connet{position: relative;  /*设置目标元素作为定位参照*/width: 100px;height: 100px;}.connet:after{   /*给目标元素添加一个伪类元素before或者after*/content: '';position: absolute;  /*设置绝对定位*/border: 1px solid red;/*为伪类元素添加1px的边框*/width: 200%;height: 200%;/*设置伪类元素的宽高为目标元素的2倍*/transform-origin:0 0;    /*伪类元素缩小0.5倍(变回目标元素的大小)*/transform: scale(0.5,0.5);box-sizing:border-box; /*把border包进来*/}</style><body><div id="box"><div class="connet"></div></div></body></html>


其运行效果图如下


明显的看到实现了0.5像素边框



原创粉丝点击