如何实现CSS边框长度独立于所属div宽度且无需额外添加HTML元素
无需额外HTML元素的自定义边框实现方案
要实现的效果如下:
目前有3种主流纯CSS方案可以实现边框长度与容器宽度独立的效果,不需要新增任何DOM节点:
方案1:线性渐变实现(代码最简)
直接通过background-image设置自定义长度的渐变模拟边框,还可以灵活调整边框的位置、长度、粗细:
#foo { height: 100px; width: 100px; background-color: red; /* 按需调整边框的大小和位置 */ background-image: linear-gradient(blue, blue); background-size: 50px 10px; /* 第一个值为边框长度,第二个为边框粗细 */ background-position: top center; /* 控制边框定位 */ background-repeat: no-repeat; }
如果需要同时设置多个不同位置的自定义边框,叠加多个渐变值即可。
方案2:伪元素实现(兼容性最好)
利用CSS生成的::before/::after伪元素模拟边框,适合更复杂的边框样式需求,兼容IE11及所有现代浏览器:
#foo { height: 100px; width: 100px; background-color: red; position: relative; } #foo::before { content: ''; position: absolute; top: 0; left: 50%; transform: translateX(-50%); width: 50px; /* 自定义边框长度 */ height: 10px; /* 自定义边框粗细 */ background-color: blue; }
方案3:border-image 实现
通过border-image配合渐变控制单边边框的显示范围:
#foo { height: 100px; width: 100px; background-color: red; border-top: 10px solid transparent; /* 25%和75%为蓝色边框的起止位置,调整数值即可修改边框长度 */ border-image: linear-gradient(to right, transparent 25%, blue 25%, blue 75%, transparent 75%) 1; }
内容的提问来源于stack exchange,提问作者shellwhale
相关产品推荐
相关产品推荐

