如何让CSS Flex与relative+absolute协同实现温度计进度条
温度计组件问题修复方案
针对你遇到的四个问题,以下是具体修复方案及完整代码:
问题1:标签(labels)不显示
原代码中CSS使用类选择器.labelRow,但HTML里对应的是id="labelRow",选择器不匹配导致标签无法显示。同时需将标签容器设置为绝对定位,避免被进度条覆盖。
问题2:分隔线置于温度计内部
将刻度分隔线移至温度计容器内,通过绝对定位实现内部分隔,移除外部冗余的rangeDisplay容器。
问题3:数字“36”和指针定位
为数字和指针添加position: absolute,通过transform: translateX(-50%)实现水平居中对齐进度条末端,调整top值让它们显示在温度计上方。
问题4:反转颜色异常
mix-blend-mode: difference在蓝色背景+白色文字下会产生米色(颜色差值计算结果),改用mix-blend-mode: exclusion可得到更接近黑白的反转效果,同时确保标签层级高于进度条。
修复后的完整代码
<html lang="en"> <head> <style> body * { box-sizing: border-box; } body { background-color: blue; margin: 20px; position: relative; } #actual { font-size: 40px; color: white; position: absolute; left: 36%; top: -50px; transform: translateX(-50%); z-index: 10; } #thermometer { border: 4px solid grey; width: 100%; height: 40px; background: darkblue; border-radius: 50vh; position: relative; overflow: hidden; } #progress { height: 100%; background: white; width: 36%; position: absolute; left: 0; top: 0; z-index: 2; } /* 内部分隔线 */ #thermometer .marker { position: absolute; top: 0; bottom: 0; border-right: 2px solid white; width: 0; z-index: 3; } #thermometer .marker:nth-child(2) { left: 25%; } #thermometer .marker:nth-child(3) { left: 50%; } #thermometer .marker:nth-child(4) { left: 75%; } #labelRow { display: flex; flex-direction: row; position: absolute; width: 100%; height: 100%; z-index: 4; } .label { flex: 1; text-align: center; padding: 8px 2px; margin: 0; color: white; mix-blend-mode: exclusion; font-weight: bold; @media only screen and (max-width: 640px) { width: 50%; } } #pointer { border-bottom: 10px solid white; border-left: 6px solid transparent; border-right: 6px solid transparent; display: inline-block; position: absolute; left: 36%; top: -10px; transform: translateX(-50%); z-index: 10; } </style> </head> <body> <div id="actual">36</div> <div id="pointer"></div> <div id="thermometer"> <div id="progress"></div> <!-- 内部分隔线 --> <div class="marker"></div> <div class="marker"></div> <div class="marker"></div> <div id="labelRow"> <div class="label">None</div> <div class="label">Low</div> <div class="label">Medium</div> <div class="label">High</div> </div> </div> </body> </html>
内容的提问来源于stack exchange,提问作者user358041
相关产品推荐
相关产品推荐

