如何使用Flexbox实现元素层叠 让单个元素显示在其他元素上方
问题原因
你当前给article元素设置的是默认横向排列的flex布局,因此同级的<h2>标题和3个地址盒子会被视为同一行的同级元素,全部参与居中对齐,自然会全部堆在一起。
修复方案
第一步:修改HTML结构
把3个地址盒子包裹在一个独立的容器中,方便单独控制这部分的排版:
<section class="banner-3"> <article> <h2 id="locations">Locations</h2> <!-- 新增地址容器 --> <div class="addresses-wrapper"> <div class="address"> <h3>Downtown</h3> <p>384 West 4th St</p> <p>Suite 108</p> <p>Portland, Maine</p> </div> <div class="address"> <h3>East Bayside</h3> <p>3433 Phisherman's Avenue</p> <p>(Northwest Corner)</p> <p>Portland, Maine</p> </div> <div class="address"> <h3>Oakdale</h3> <p>515 Crescent Avenue</p> <p>Second Floor</p> <p>Portland, Maine</p> </div> </div> </article> </section>
第二步:修改CSS样式
调整article的flex布局方向为垂直排列,同时给新增的地址容器设置横向flex布局:
.banner-3 article { height: 500px; width: 1200px; background-image: url("../images/img-locations-background.jpg"); background-repeat: no-repeat; background-position-y: center; background-size: cover; margin: 0 auto; margin-top: 2.5%; /* 原来的inline-flex改为flex,设置垂直排列 */ display: flex; flex-direction: column; justify-content: center; /* 垂直方向整体居中 */ align-items: center; /* 所有子元素水平居中 */ gap: 15px; /* 标题和地址容器的间距,可自行调整 */ } /* 新增地址容器样式 */ .addresses-wrapper { display: flex; justify-content: center; align-items: center; } .banner-3 .address { width: 300px; height: 300px; display: flex; flex-direction: column; align-content: center; justify-content: center; background-color: black; opacity: 1; margin: 20px; } .address h3, p { margin: 25px auto; }
如果不想新增HTML容器,也可以用绝对定位单独固定标题的位置,不过新增容器的方案语义化更好,后期调整也更灵活。
内容的提问来源于stack exchange,提问作者Nima Zarei
相关产品推荐
相关产品推荐

