今天来讲多重边框
在一些场景中,我们要给元素设置很多个边框,这时你或许会让多个元素通过定位一层层覆盖,可是这样既浪费了元素,而且还吃力,,所以今天来介绍两种其他方案:
box-shadow
直接上代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>多重边框</title> <style type="text/css" media="screen"> html{ height:100%; } body{ display:flex; height:100%; margin:0; } div{ width:200px; height:150px; margin:auto; background:green; box-shadow:0 0 0 10px #fc4766, 0 0 0 15px lime, 0 2px 5px 15px rgba(0,0,0,.6) }
</style> </head> <body> <div> </div>
</body>
|
;
使用box-shadow
的好处就是你可以通过逗号来分割多个值已到达多个边框的效果,同时他也不会占据空间,如果你要其占据空间,可以使用内边距或外边距来模拟,同时他还可以设置内圈边框,使用inset
outline
如果你要使用两层边框,可以使用outline
搭配元素本身的边框来实现,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>多重边框</title> <style type="text/css" media="screen"> html{ height:100%; } body{ display:flex; height:100%; margin:0; }
不过只适用于两层边框,所以要先设置一层常规额边框,然后再加上outline产生外层边框 box-shadow只能模拟实线边框,而outline能模拟虚线边框 */ div{ width:200px; height:150px; background:#fc4766; border:1px solid lime; outline:5px dashed deeppink; outline-offset:5px; margin:auto; }
</style> </head> <body> <div> </div>
</body> </html>
|
同样的他也不会占据空间,而且可以搭配outline-offset
来设置其与元素边缘的距离,不过他不一定会贴合边框的圆角,后文会提供解决方法,
另外outline
还存在一个层级的问题,我从网上百度了一下,发现下面一篇文章写的挺详细的,可以一阅:
outline的层级问题