如何为空锚点标签添加背景图并使文本位于图片下方20px?
解决文本叠加在背景图上的问题
你的核心问题是把背景图加在了父容器.splitpage上,而空的<a>标签没有设置宽高,相当于没有占位,导致整个父容器被背景图铺满,文本直接叠加在背景图上方。下面是具体的修复方案:
步骤1:调整背景图的挂载对象
把背景图从.splitpage移到<a>标签上,同时给<a>设置宽高,让它能正常显示图片:
#pants a { background: url(layout1-assets/pants.webp); background-size: cover; display: block; /* 让a标签能设置宽高 */ width: 100%; height: 300px; /* 根据需求调整高度,也可以用宽高比替代 */ } #shirts a { background: url(layout1-assets/shirts.webp); background-size: cover; display: block; width: 100%; height: 300px; }
同时删除原来加在.splitpage上的背景图样式:
/* 移除这两行 */ #pants { background: url(...); background-size: cover; } #shirts { background: url(...); background-size: cover; }
步骤2:让.splitpage垂直排列内容
给.splitpage设置垂直方向的flex布局,这样图片(<a>)和文本就能自动上下排列,还能保持响应式:
.splitpage { width: 50%; margin: 0; text-align: center; display: flex; /* 新增 */ flex-direction: column; /* 垂直排列子元素 */ gap: 20px; /* 图片和文本之间的间距,正好是你要的20px */ }
这时候可以删掉原来给#store p加的padding-top:20px,因为gap已经控制了整体间距。
修改后的完整代码
CSS
#store { overflow: auto; padding: 40px 0; } .splitpage { width: 50%; margin: 0; text-align: center; display: flex; flex-direction: column; gap: 20px; } .container { width: 1040px; margin: 0 auto; } .flex { display: flex; justify-content: space-between; } .wrap { flex-wrap: wrap; } #pants a { background: url(layout1-assets/pants.webp); background-size: cover; display: block; width: 100%; height: 300px; } #shirts a { background: url(layout1-assets/shirts.webp); background-size: cover; display: block; width: 100%; height: 300px; }
HTML
<section id="store"> <div class="container flex wrap"> <div class="splitpage" id="pants"> <a href="#" aria-label="photo of our various types of pants"></a> <h2>Our pants</h2> <p>Description of pants here</p> </div> <div class="splitpage" id="shirts"> <a href="#" aria-label="photo of our various shirts"></a> <h2>Our shirts</h2> <p>Description of shirts here</p> </div> </section>
额外优化建议
- 如果想让图片高度自适应屏幕缩放,可以把
height:300px改成aspect-ratio: 4/3;(设置固定宽高比,比如4:3),这样图片会保持比例自动调整尺寸。 - 给
<a>标签加min-height: 200px,避免在小屏幕上图片高度过矮。
内容的提问来源于stack exchange,提问作者ellekatdub
相关产品推荐
相关产品推荐

