如何用CSS仅缩放图片左侧5px区域,右侧保持固定?
实现仅图片左侧5px区域拉伸的CSS方案
核心思路
将图片拆分为左侧可拉伸区和右侧固定区:左侧区域基于原图左侧5px截取,随容器宽度扩展而横向拉伸;右侧区域保留原图剩余部分,固定宽度并锚定在容器右侧。
修正后的完整代码方案(伪元素实现)
<div class="stretchable-image"></div>
.stretchable-image { /* 初始宽度可按需调整,拉伸时修改此值即可 */ width: 400px; height: 200px; position: relative; overflow: hidden; } /* 左侧可拉伸区域 */ .stretchable-image::before { content: ''; position: absolute; top: 0; left: 0; /* 宽度 = 容器总宽度 - 右侧固定区域宽度(需替换为「原图总宽度-5px」) */ width: calc(100% - 390px); height: 100%; background-image: url('image_url.png'); /* 仅截取原图左侧5px的部分 */ background-position: 0 0; background-size: 5px 100%; background-repeat: no-repeat; } /* 右侧固定区域 */ .stretchable-image::after { content: ''; position: absolute; top: 0; right: 0; /* 宽度 = 原图总宽度 - 5px */ width: 390px; height: 100%; background-image: url('image_url.png'); /* 显示原图右侧剩余部分 */ background-position: right 0; background-size: auto 100%; background-repeat: no-repeat; }
更直观的Flex布局方案
<div class="stretchable-image"> <div class="stretch-left"></div> <div class="stretch-right"></div> </div>
.stretchable-image { display: flex; width: 400px; height: 200px; } /* 左侧自动填充剩余空间并拉伸 */ .stretch-left { flex: 1; background-image: url('image_url.png'); background-position: 0 0; background-size: 5px 100%; } /* 右侧固定宽度,保持原图比例 */ .stretch-right { width: 390px; /* 替换为「原图总宽度-5px」 */ background-image: url('image_url.png'); background-position: right 0; background-size: auto 100%; }
你原有代码的问题说明
calc(100% -5px)缺少空格:CSS中calc运算符前后必须加空格,否则语法无效;- 伪元素
::after的height属性后未加分号,导致CSS解析错误; - 同时使用
<img>标签和伪元素,造成图片重复显示,需移除冗余的<img>; - 未通过
background-size精准截取图片区域,无法实现局部拉伸效果。
内容的提问来源于stack exchange,提问作者user23211109
相关产品推荐
相关产品推荐

