如何实现将logo放置在两个section区块中间且不属于任意区块
实现方案
方案1:修复现有绝对定位写法
你当前用position: absolute的思路是可行的,只需要调整两处即可实现图片固定卡在两个section中间,不归属于任意section:
- 给
<body>添加position: relative属性,让图片的绝对定位以整个页面内容为基准,滚动页面时图片会跟随内容移动,不会固定在屏幕视口位置 - 给img的style添加
top: 350px属性:第一个section高度为400px,图片自身高度为100px,设置top为400-50=350px时,图片刚好一半在上方蓝色section、一半在下方黄色section,处于两个区块的中间位置
修改后的完整代码如下:
<body style="position: relative; margin: 0; padding: 0;"> <section class="parent" style="height: 400px; background-color: blue"> <div class="boxparent" style=" top: 10px;"> </div> </section> <img src="https://place-hold.it/100x100.jpg/666/fff/000" style="position: absolute;background-color: #254543;z-index: 1; left: 25%; top: 350px; "> <section class="parent" style="height: 400px; background-color: yellow;"> <div class="boxparent"> </div> </section> </body>
方案2:更灵活的负margin方案(推荐适配响应式场景)
如果你的section高度不是固定值,不想手动计算top值,可以用相对定位+负margin的方案,不需要给父元素加定位属性:
- 给img设置
position: relative保留在正常文档流位置,同时设置margin-top: -50px(等于图片高度的一半),让图片向上偏移自身高度的一半,刚好卡在两个section的交界处 - 可以通过调整
margin-left或者left属性控制水平位置,比绝对定位适配性更强,不需要依赖父容器定位
对应代码如下:
<body style="margin: 0; padding: 0;"> <section class="parent" style="height: 400px; background-color: blue"> <div class="boxparent" style=" top: 10px;"> </div> </section> <img src="https://place-hold.it/100x100.jpg/666/fff/000" style="position: relative;background-color: #254543;z-index: 1; margin-left: 25%; margin-top: -50px;"> <section class="parent" style="height: 400px; background-color: yellow;"> <div class="boxparent"> </div> </section> </body>
内容的提问来源于stack exchange,提问作者M K
相关产品推荐
相关产品推荐

