如何在CSS/Div容器中调整背景图片尺寸?(350×80改300×70)
调整Div背景图片尺寸的解决方案
嘿,刚好能帮到你!要实现不用PS、纯代码调整Div背景图到指定尺寸(300×70),核心是利用CSS的background-size属性,直接看修改后的代码和细节说明:
关键修改点
- 给背景图容器添加
background-size属性,精确指定目标尺寸,配合background-repeat: no-repeat避免背景图重复 - 修正你原代码里的内联样式语法错误(比如
height="70";的分号位置错误) - 建议把内联样式移到CSS类中,更便于后续维护
修改后的完整代码
body { background-color: #6B6B6B; font-family: Arial; color: darkgrey; font-size: 12px; line-height: .2; letter-spacing: .5px; } /*.............. info ..............*/ .info { position: fixed; top: 30px; left: 30px; grid-template-columns: 60px 300px; display: grid; } /* 新增背景图容器的CSS类 */ .bubble-container { width: 300px; height: 70px; background-image: url('http://wizzfree.com/pix/bubble.png'); background-size: 300px 70px; /* 关键:指定背景图尺寸和容器一致 */ background-repeat: no-repeat; /* 防止背景图重复平铺 */ padding: 0 8px; /* 可选:给文字加内边距避免贴边 */ } /* 优化文字排版,避免过于拥挤 */ .bubble-container p { margin: 3px 0; line-height: 1.1; /* 单独调整行高,让文字更易读 */ }
<div class="info" align="center"> <div><img src="http://wizzfree.com/pix/profile.png" class="bevel2" width="60" height="60"/></div> <div class="bubble-container"> <p>chat text some chat text here some text</p> <p>here some chat text here some text here some</p> <p>chat text here some text here some chat text</p> <p>chat text here some text here some chat text</p> </div> </div>
细节说明
background-size: 300px 70px:这是核心属性,它会强制背景图缩放到你需要的精确尺寸,和容器宽高完全匹配,不需要提前用PS修改原图,就能达到你要的300×70效果。- 样式分离的好处:把样式从内联移到CSS类中,后续要调整尺寸、背景色或排版时,只需要修改一处代码,更高效也更规范。
- 文字排版优化:原代码里全局的
line-height: .2会导致文字挤在一起,我给容器内的p标签单独调整了行高,你可以根据自己的需求再微调数值。
这样既满足了你不用PS、不用表格的要求,又能通过代码精确控制背景图尺寸,保证清晰的显示效果哦!
内容的提问来源于stack exchange,提问作者Yummi
相关产品推荐
相关产品推荐

