You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

绝对定位元素card3脱离父容器sec2显示在sec1的问题排查

解决absolute定位元素脱离父容器的问题

问题原因

使用position: absolute的元素,定位参考对象是最近的非static定位父元素。你的sec2容器默认是position: static(未设置定位属性时的默认值),因此card3会相对于整个文档(body)定位,导致出现在sec1区域。

解决方案

给sec2添加position: relative属性,将其设置为card3的定位上下文,这样card3就会以sec2为基准进行定位,固定在sec2区域内。

修改后的代码

HTML代码(修改sec2的样式)

<section class="sec2" style="background-color:#0e1525 ; position: relative;">
    <div class="intro" id="intro" style="width: 100%; height: 100vh;align-content: center;display: grid;grid-template-rows: 1fr 1fr;grid-template-columns: 1fr 1fr;">
        <h1 style="margin-inline: auto;text-align: left;grid-row: 1;font-size: 10vh;font-family:'Roboto'; color: white;align-content: center;">Plants and Fire</h1>
    
        <p style="grid-row: 2;color: white;font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;text-align: center;width: 80%;margin: auto;">
            Lorem ipsum, dolotrum?
        </p>
    </div>
    <div class="card3" id="car3">
        <h1>hello world</h1>
    </div>
</section>

CSS代码(无需修改,保持原样式即可)

.card3 {
    width: var(--card3-width);
    height: var(--card3-height);
    z-index: 1;
    border-radius: 1vh;
    justify-content: center;
    align-items: center;
    text-align: center;
    font-size: 1.5vh;
    color: white;
    align-self: center;
    position: absolute;
    top: 20vh;
    right: 20vh;
    transition: 1s ease-in-out;
    border-width: 1vh;
    background-image: linear-gradient(#5ddcff, #3c67e3 43%,#4e00c2);
}

补充说明

添加position: relative不会改变sec2本身的布局结构,仅为内部的绝对定位元素提供定位基准。如果需要调整card3在sec2内的位置,直接修改top、right等定位属性即可。

内容的提问来源于stack exchange,提问作者Harshit singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 16:35:18