如何解决两个div容器内的图片发生重叠的问题
问题原因
你当前的.home__img使用了相对于全局视口的绝对定位,新增头部图片后占用了顶部空间,原定位规则没有适配新增的头部内容,同时你现有HTML中头部的<section>标签未闭合,两个问题共同导致了图片重叠。
解决方案
1. 先修正HTML结构
给头部的section补充闭合标签,避免结构嵌套错乱:
<section> <div class="header-img"> <img src="assets/images/header-img.png" alt=""> </div> </section> <!-- 补充这行闭合标签 --> <section class="home bd-grid" id="home"> <!-- 原有home区块内容保持不变 --> <div class="home__data"> <h1 class="home__title">Hi, I'm <span class="home__title__color">Tahmid Mahi</span><br> Web Developer</h1> <a target="_blank" href="https://m.me/mmaitomm" class="button">Contact</a> </div> <div class="home__social"> <a target="_blank" href="https://www.facebook.com/mmaitomm" class="home__social-icon"><i class='bx bxl-facebook' ></i></a> <a target="_blank" href="https://www.instagram.com/medffee" class="home__social-icon"><i class='bx bxl-instagram' ></i></a> <a target="_blank" href="https://www.github.com/tahmidmahi04" class="home__social-icon"><i class='bx bxl-github' ></i></a> <a target="_blank" href="https://www.tiny.one/maiiiwall" class="home__social-icon"><i class='bx bxl-android' ></i></a> </div> <div class="home__img"> <img src="assets/images/perfil.png" alt=""> </div> </section>
2. 替换原有CSS样式
/* 头部图片样式 */ .header-img { width: 100%; /* 如果需要head.png固定在视口顶部不随滚动消失,取消下面三行注释,把120替换成你的header图片实际高度 */ /* position: sticky; top: 0; z-index: 999; */ } .header-img img { width: 100%; height: auto; display: block; /* 清除图片默认底部空白间隙 */ } /* 给home容器加相对定位,限制内部绝对定位元素仅在home区块内生效 */ .home { position: relative; /* 如果header是固定定位,取消下面一行注释,120替换为header图片实际高度 */ /* min-height: calc(100vh - 120px); */ padding-top: 2rem; /* 调整和头部图片的上下间距,可按需修改 */ } /* 修改home__img定位规则,实现和左侧文本垂直对齐 */ .home__img{ position: absolute; right: 0; top: 50%; /* 相对于home区块垂直居中 */ transform: translateY(-50%); /* 修正自身高度带来的居中偏移 */ width: 295px; } @media screen and (min-width: 768px){ .home__img{ width: 457px; } } @media screen and (min-width: 1024px){ .home__img{ right: 10%; } }
微调说明
如果对齐效果不符合预期,可以微调.home__img的top属性值(比如改成48%、52%),直到和左侧「Hi I'm...」文本对齐即可。
内容的提问来源于stack exchange,提问作者Tahmid Mahi
相关产品推荐
相关产品推荐

