(编辑:jimmy 日期: 2024/10/30 浏览:2)
在工作中想要实现如下效果:
在 div 标签中添加一个 relative 定位,然后使用绝对定位 absolute 在最右侧
<div class="content"> <div class="bar first" style="width:100%"> <span>688</span> </div> <div class="bar second" style="width:50%"> <span>688</span> </div> <div class="bar third" style="width:80%"> <span>688</span> </div> </div>
自己的解决办法
.bar { height: 12px; margin-top: 1px; position: relative; &.first { background-image: linear-gradient(90deg, #ecf848 0%, #f9eab9 99%); } &.second { background-image: linear-gradient(90deg, #f5b549 0%, #f9d6b9 100%); } &.third { background-image: linear-gradient(90deg, #f57849 0%, #f9c7b9 100%); } span{ position: absolute; right: 0; font-size: 12px; color: rgba(255, 255, 255, 0.7); } }
结果:
按照上面的写法,只能是 span 标签的最右侧和父标签div 的最右侧重叠,无法实现目标。解决办法,计算 span标签的值,然后right 设置为计算的长度
.bar { height: 12px; margin-top: 1px; position: relative; &.first { background-image: linear-gradient(90deg, #ecf848 0%, #f9eab9 99%); } &.second { background-image: linear-gradient(90deg, #f5b549 0%, #f9d6b9 100%); } &.third { background-image: linear-gradient(90deg, #f57849 0%, #f9c7b9 100%); } span{ position: absolute; left: calc(100% + 8px); font-size: 12px; color: rgba(255, 255, 255, 0.7); } }
left 参照的宽度是 父容器 的宽度
.bar { height: 12px; margin-top: 1px; position: relative; &.first { background-image: linear-gradient(90deg, #ecf848 0%, #f9eab9 99%); } &.second { background-image: linear-gradient(90deg, #f5b549 0%, #f9d6b9 100%); } &.third { background-image: linear-gradient(90deg, #f57849 0%, #f9c7b9 100%); } span{ position: absolute; right:0; transform: translate(100%, 0); font-size: 12px; color: rgba(255, 255, 255, 0.7); } }
transform: translate 参照的宽度是自身内容的宽度