CSS边框:如何实现减切式边框?
可以用CSS实现这类边框
当然可以!这类分段式边框(你可以用这个关键词搜索相关方案)完全能用CSS实现,下面给你两种实用方案:
方法一:伪元素 + 边框拆分
适合需要单独调整每段边框样式的场景:
.box { position: relative; width: 300px; height: 200px; padding: 2rem; } /* 生成上下边的左右两段 */ .box::before { content: ""; position: absolute; top: 0; bottom: 0; left: 2rem; right: 2rem; border-top: 2px solid #222; border-bottom: 2px solid #222; } /* 生成左右边的上下两段 */ .box::after { content: ""; position: absolute; left: 0; right: 0; top: 2rem; bottom: 2rem; border-left: 2px solid #222; border-right: 2px solid #222; }
方法二:背景渐变拼接
代码更简洁,适合边框样式统一的场景:
.box { width: 300px; height: 200px; padding: 2rem; /* 通过8条线性渐变拼接成分段边框 */ background: linear-gradient(#222, #222) top left / calc(50% - 2.5rem) 2px, linear-gradient(#222, #222) top right / calc(50% - 2.5rem) 2px, linear-gradient(#222, #222) bottom left / calc(50% - 2.5rem) 2px, linear-gradient(#222, #222) bottom right / calc(50% - 2.5rem) 2px, linear-gradient(#222, #222) top left / 2px calc(50% - 2.5rem), linear-gradient(#222, #222) top right / 2px calc(50% - 2.5rem), linear-gradient(#222, #222) bottom left / 2px calc(50% - 2.5rem), linear-gradient(#222, #222) bottom right / 2px calc(50% - 2.5rem); background-repeat: no-repeat; }
你可以修改代码里的数值(比如2rem、2.5rem)来调整边框段的长度和间距,替换#222改变边框颜色。
内容的提问来源于stack exchange,提问作者Ena
相关产品推荐
相关产品推荐

