如何用HTML和CSS创建带指定百分比长度边框的矩形
实现顶部中心起始的百分比长度边框矩形
可以通过CSS线性渐变或者伪元素来实现这种自定义边框效果,以下是两种简单可行的方案:
方案一:线性渐变实现(无额外HTML元素)
这种方法通过多层背景渐变模拟分段边框,百分比直接基于元素宽度计算,符合需求:
<div class="box left-box"></div> <div class="box right-box"></div>
.box { width: 200px; height: 250px; margin: 2rem; background-color: #f5f5f5; } /* 左侧矩形:顶部中心向左30%宽度的边框,延伸到底部再回到中心 */ .left-box { background-image: /* 顶部边框:从中心向左覆盖30%宽度 */ linear-gradient(90deg, transparent calc(50% - 30%), #333 calc(50% - 30%), #333 50%, transparent 50%), /* 左侧边框:从顶部边框端点垂直延伸到底部 */ linear-gradient(180deg, #333 0%, #333 100%), /* 底部边框:从左侧端点向右覆盖30%宽度到中心 */ linear-gradient(90deg, #333 0%, #333 30%, transparent 30%); background-size: 100% 2px, /* 顶部边框尺寸 */ 2px 100%, /* 左侧边框尺寸 */ 100% 2px; /* 底部边框尺寸 */ background-position: top center, calc(50% - 30%) top, bottom calc(50% - 30%); background-repeat: no-repeat; } /* 右侧矩形:顶部中心向右45%宽度的边框,延伸到底部再回到中心 */ .right-box { background-image: /* 顶部边框:从中心向右覆盖45%宽度 */ linear-gradient(90deg, transparent 50%, #333 50%, #333 calc(50% + 45%), transparent calc(50% + 45%)), /* 右侧边框:从顶部边框端点垂直延伸到底部 */ linear-gradient(180deg, #333 0%, #333 100%), /* 底部边框:从右侧端点向左覆盖45%宽度到中心 */ linear-gradient(90deg, transparent calc(100% - 45%), #333 calc(100% - 45%), #333 100%, transparent 100%); background-size: 100% 2px, 2px 100%, 100% 2px; background-position: top center, calc(50% + 45%) top, bottom calc(50% + 45%); background-repeat: no-repeat; }
方案二:伪元素实现(更易调整细节)
如果需要更灵活的边框样式(比如圆角、不同段颜色),可以用伪元素单独绘制每段边框:
<div class="box left-box"> <div class="bottom-border"></div> </div> <div class="box right-box"> <div class="bottom-border"></div> </div>
.box { width: 200px; height: 250px; margin: 2rem; position: relative; background-color: #f5f5f5; } /* 左侧矩形边框 */ .left-box::before { content: ''; position: absolute; /* 顶部边框:从中心向左30%宽度 */ top: 0; left: 50%; width: 30%; height: 2px; background-color: #333; transform: translateX(-100%); } .left-box::after { content: ''; position: absolute; /* 左侧边框:从顶部边框端点垂直到底部 */ top: 0; left: calc(50% - 30%); width: 2px; height: 100%; background-color: #333; } .left-box .bottom-border { position: absolute; /* 底部边框:从左侧端点向右30%宽度到中心 */ bottom: 0; left: calc(50% - 30%); width: 30%; height: 2px; background-color: #333; } /* 右侧矩形边框 */ .right-box::before { content: ''; position: absolute; /* 顶部边框:从中心向右45%宽度 */ top: 0; left: 50%; width: 45%; height: 2px; background-color: #333; } .right-box::after { content: ''; position: absolute; /* 右侧边框:从顶部边框端点垂直到底部 */ top: 0; right: calc(50% - 45%); width: 2px; height: 100%; background-color: #333; } .right-box .bottom-border { position: absolute; /* 底部边框:从右侧端点向左45%宽度到中心 */ bottom: 0; right: calc(50% - 45%); width: 45%; height: 2px; background-color: #333; }
内容的提问来源于stack exchange,提问作者anonymous
相关产品推荐
相关产品推荐

