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

如何让Div仅在X轴固定于屏幕中间,Y轴随滚动移动?

实现X轴始终居中、Y轴随页面滚动的Div元素

需求:让一个Div元素固定在屏幕X轴中间,左右滚动时保持居中位置;上下滚动时,如同relative定位一样随页面滚动消失。

原问题:使用position: fixed会导致X、Y轴均固定,无法满足上下滚动随页面消失的需求。

解决方案代码

CSS 代码

.text{
    text-align:center;
}

#header {
    position: sticky;
    left: 50%;
    width: 200px;
    height: 160px;
    /* 也可以用 left: calc(50% - 100px); 替代transform */
    transform: translateX(-50%);
}

#image{
    position: relative;
    display: block;
    margin: auto;
    width: 1200px;
    height:600px;
    z-index:2;
    overflow:clip;
}

#div{
    position: relative;
    display:block;
    margin: auto;
    height: 600px;
    width: 1200px;
    border: 5px solid black;
    background:linear-gradient(#1a1536,rgb(40, 9, 90), rgb(18, 29, 87),#1a1536);
    z-index:1;
    overflow:clip;
}

HTML 代码

<div id="header">
    <h1 class="text">Title</h1>
    <h3 class="text">SubTitle</h3>
    <h2 class="text">SubTitle</h2>
</div>

<div id="div">
    <img class="place" id="image" src="https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.iconsdb.com%2Flight-gray-icons%2Fsquare-icon.html&psig=AOvVaw1fzZXNZn7_2YEF6WDUukgV&ust=1722012245418000&source=images&cd=vfe&opi=89978449&ved=0CA8QjRxqFwoTCPjMyNPRwocDFQAAAAAdAAAAABAE">
</div>

操作说明

进入全屏代码片段模式,缩小窗口至需要滚动查看图片的状态,向右滚动时#header会保持屏幕居中位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 16:03:10