如何让进度条达到100%时不超出地图边界?
进度条贴合地图内侧边界的解决方案
我的进度条从中心向左右两侧等量扩展至100%时,会略微超出地图边界,希望进度条满值时刚好贴合地图内侧边界,不超出范围。
现有进度条CSS代码
body { margin:0px auto; padding:0px; font-family:helvetica; } .progress { position: relative; left: 0px; top: 0px; width: 100%; height: 100%; z-index: 9999; background-color: #F2F2F2; } .bar { background-color: #819FF7; width:0%; height:5px; border-radius: 3px; margin-left: 10%; } .percent { position:absolute; display:inline-block; top:3px; left:48%; } .center-screen { display: flex; justify-content: center; align-items: center; min-height: 100vh; flex-direction: column; } #wrapper { width:995px; padding:0px; margin:0px auto; font-family:helvetica; text-align:center; } h1 { text-align:center; font-size:35px; margin-top:60px; color:#A9BCF5; } h1 p { text-align:center; margin:0px; font-size:18px; text-decoration:underline; color:grey; }
现有地图CSS代码
#map { width: 1600px; height:850px; margin: 0; position: absolute; top: 48%; left: 50%; margin-right: -50%; transform: translate(-50%, -50%) } #map.fullscreen { position: fixed; width:100%; height: 100%; }
已尝试的方法
- 曾在HTML中创建父容器
MyContainer,将进度条和地图放入其中并设置width:100%,但进度条移到屏幕顶部,问题未解决。 - 尝试创建在线演示,但进度条完全不显示。
解决方案
1. 调整进度条容器定位与范围
修改.progress的CSS,让它依附于地图容器,避免脱离范围:
.progress { position: absolute; /* 改为绝对定位,跟随地图容器 */ left: 0; top: 0; width: 100%; height: auto; /* 高度自适应,仅包裹进度条元素 */ z-index: 9999; background-color: transparent; /* 移除背景色,避免遮挡地图 */ }
2. 实现进度条中心对称扩展且不越界
修改.bar的样式,通过定位和变换实现中心扩展,同时限制最大宽度:
.bar { background-color: #819FF7; width:0%; height:5px; border-radius: 3px; position: absolute; /* 绝对定位 */ left: 50%; /* 初始位置对齐地图中心 */ transform: translateX(-50%); /* 向左偏移自身一半宽度,确保中心起点 */ max-width: 100%; /* 最大宽度不超过地图容器 */ }
当进度条宽度从0增加到100%时,会以地图中心为起点向两侧等量扩展,且最大宽度严格匹配地图内侧宽度,不会超出边界。
3. 嵌套进度条到地图容器
在HTML中将进度条元素放入#map容器内部,确保进度条的宽度受限于地图:
<div id="map"> <div class="progress"> <div class="bar"></div> <div class="percent">0%</div> </div> <!-- 地图原有内容 --> </div>
4. 调整百分比文本居中
修改.percent的样式,让它始终在进度条上方居中显示:
.percent { position:absolute; display:inline-block; top: 10px; /* 调整与进度条的垂直距离 */ left: 50%; transform: translateX(-50%); /* 水平居中对齐 */ margin: 0; }
内容的提问来源于stack exchange,提问作者Daniel Lip
相关产品推荐
相关产品推荐

