如何用HTML制作带图文的主横幅并解决内容重叠问题
问题分析与修复方案
一、修复现有代码的问题
你的代码存在3个核心问题,调整后即可解决内容错位、遮挡的问题:
1. 移除重复的图片资源
.banner类已经通过background-image设置了背景图,但HTML中又嵌套了<img>标签,这会导致图片重复加载且布局冲突,直接删除该<img>标签即可。
2. 调整横幅高度与文字定位
当前.banner的height:100px过小,完全容纳不下内部大字号的标题,且.banner-text的top:140px会让文字直接跑到横幅容器外,脱离文档流后导致后续内容被遮挡。修改代码如下:
.banner { background-image: url(https://s3.amazonaws.com/shecodesio-production/uploads/files/000/055/950/original/Icelandheadingphoto.jpg?1669912436); background-repeat: no-repeat; background-position: center; /* 调整为最小高度,确保能容纳标题,比固定高度更灵活 */ min-height: 300px; position: relative; background-size: cover; } .banner-text { color: #fff; position: absolute; /* 调整top值让文字在横幅内部,搭配transform实现垂直居中 */ top: 50%; left: 120px; transform: translateY(-50%); }
3. 清除默认样式干扰(可选但推荐)
浏览器默认会给body、h1等元素添加margin,可能导致布局偏移,在CSS开头添加全局重置代码:
* { margin: 0; padding: 0; box-sizing: border-box; }
二、更简洁的横幅重做思路
如果想换一种更易维护的方式,推荐使用语义化结构配合定位实现:
<div class="banner"> <figure> <img src="https://s3.amazonaws.com/shecodesio-production/uploads/files/000/055/950/original/Icelandheadingphoto.jpg?1669912436" alt="iceland"> <figcaption class="banner-text"> <h1>Iceland</h1> <h2>"The land of fire and Ice"<br>3 places you MUST visit!</h2> </figcaption> </figure> </div>
对应的CSS:
.banner figure { position: relative; width: 100%; margin: 0; } .banner img { width: 100%; height: auto; display: block; } .banner-text { position: absolute; top: 50%; left: 120px; transform: translateY(-50%); color: #fff; } .banner-text h1 { font-size: 100px; font-family: fantasy; margin: 0; } .banner-text h2 { font-size: 30px; font-family: fantasy; margin: 0; }
这种方式符合HTML语义化规范,逻辑更清晰,后续调整也更方便。
内容的提问来源于stack exchange,提问作者Marley
相关产品推荐
相关产品推荐

