如何用HTML和CSS在图片指定位置放置文本并适配全屏幕
实现方案
要让文本固定在图片的特定位置且在所有屏幕上位置一致,核心用CSS定位就能实现,具体操作如下:
1. 调整HTML结构
把图片和所有文本放进一个容器中,作为定位的基准容器:
<div class="image-container"> <img alt="star" src="star.png" /> <p class="text-item">Text</p> <p class="text-item">Text</p> <p class="text-item">Text</p> <p class="text-item">Text</p> <p class="text-item">Text</p> </div>
2. 添加CSS样式
通过相对定位容器、绝对定位文本,固定文本相对于图片的位置:
/* 容器设为相对定位,作为绝对定位元素的参考基准 */ .image-container { position: relative; /* 让容器宽度和图片一致,避免多余空白导致定位偏移 */ display: inline-block; } /* 保证图片自适应屏幕,同时比例不变 */ .image-container img { width: 100%; height: auto; } /* 给每个文本单独设置定位,按需调整top/left值匹配目标效果 */ .text-item:nth-child(2) { position: absolute; top: 15%; /* 距离图片顶部的百分比 */ left: 25%; /* 距离图片左侧的百分比 */ } .text-item:nth-child(3) { position: absolute; top: 35%; left: 75%; } .text-item:nth-child(4) { position: absolute; top: 55%; left: 20%; } .text-item:nth-child(5) { position: absolute; top: 75%; left: 65%; } .text-item:nth-child(6) { position: absolute; top: 90%; left: 45%; }
关键说明
- 使用百分比单位设置top/left,能确保在不同屏幕尺寸下,文本相对于图片的位置始终一致;如果需要固定像素级位置,也可以替换为px单位,但适配性会有所下降。
display: inline-block让容器仅占据图片的宽度,避免容器过宽导致定位偏差。- 通过
:nth-child选择器可以精准控制每一段文本的位置,完全匹配你想要的布局效果。
内容的提问来源于stack exchange,提问作者CodeLover
相关产品推荐
相关产品推荐

