如何为div的四个角添加带圆角属性的伪元素装饰?
用两个伪元素为div添加四个角的圆角边框装饰
我已经实现了为class为div的元素左上角添加带圆角的红色边框伪元素,代码如下:
原CSS代码
html{ box-sizing: border-box; font-size: 100%; } *, *::before, *::after{ margin: 0; padding: 0; box-sizing: inherit; } .div{ position: absolute; top: 50%; left: 50%; background-color: hsla(0, 100%, 50%, 0.151); transform: translate(-50%,-50%); padding: 10px 40px; } .div::after{ content: ''; position: absolute; top: 0; left: 0; width: 10px; height: 10px; border-left: 1px solid red; border-top: 1px solid red; border-radius: 3px 0px 0px 0px; }
原HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="/style.css"> <title>Document</title> </head> <body> <div class="div"> <p>hello</p> </div> </body> </html>
现在我想为该div的四个角都添加相同圆角属性的伪元素装饰,但只能使用::before和::after两个伪元素,请问该如何实现?
解决方案
可以利用CSS Clip-path属性,让每个伪元素同时生成两个对角的装饰,具体代码如下:
修改后的CSS代码
html{ box-sizing: border-box; font-size: 100%; } *, *::before, *::after{ margin: 0; padding: 0; box-sizing: inherit; } .div{ position: absolute; top: 50%; left: 50%; background-color: hsla(0, 100%, 50%, 0.151); transform: translate(-50%,-50%); padding: 10px 40px; /* 设置相对定位,作为伪元素的定位基准 */ position: relative; } /* 用before实现左上角和右下角的装饰 */ .div::before { content: ''; position: absolute; top: 0; left: 0; right: 0; bottom: 0; border-top: 1px solid red; border-left: 1px solid red; border-bottom: 1px solid red; border-right: 1px solid red; border-radius: 3px; /* 裁剪出仅显示左上角和右下角的10px区域 */ clip-path: inset(0 calc(100% - 10px) calc(100% - 10px) 0); } /* 用after实现右上角和左下角的装饰 */ .div::after { content: ''; position: absolute; top: 0; left: 0; right: 0; bottom: 0; border-top: 1px solid red; border-right: 1px solid red; border-bottom: 1px solid red; border-left: 1px solid red; border-radius: 3px; /* 裁剪出仅显示右上角和左下角的10px区域 */ clip-path: inset(calc(100% - 10px) 0 0 calc(100% - 10px)); }
原理说明
- 给父元素
.div添加position: relative,确保伪元素基于父元素定位。 - 每个伪元素都设置为覆盖整个父元素的尺寸,通过
clip-path: inset()裁剪出仅显示两个对角的10px区域,实现一个伪元素对应两个角的装饰。 inset()函数的四个参数依次对应上、右、下、左的裁剪距离,calc(100% - 10px)表示从对应方向裁剪到只剩10px的区域。
内容的提问来源于stack exchange,提问作者Emmanuel Maurice
相关产品推荐
相关产品推荐

