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

使用display:flex时div从relative到fixed定位过渡失效问题求解

问题原因

你的过渡失效核心有两个原因:

  1. CSS transition 不支持position属性的状态切换,你从position: relative直接切换到position: fixed时,元素的定位上下文从父级#content-1直接变成视口,没有中间过渡状态,因此会直接跳转。
  2. 两个状态类的可过渡属性没有统一声明:.page-name没有定义top、left的初始值,切换到.fixed-header时这两个属性属于新增属性,transition无法对未初始化的属性做过渡计算。
    同时你当前的.fixed-header没有定义更小的字号/内边距,也不会实现标题缩小的效果。

修复方案

不需要修改JS和HTML代码,仅调整CSS部分即可:

  1. 统一标题的定位类型为fixed,避免切换position属性
  2. 用transform配合top、left实现首屏居中、吸顶两个状态的定位,所有属性都设置明确的初始值和切换值
  3. 给吸顶状态添加更小的字号和内边距,实现尺寸缩小效果

修改后的CSS代码:

* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

#content-1 {
  width: 100vw;
  height: 100vh;
  background-color: green;
  /* display:flex相关属性可以保留也可以删除,不影响标题定位 */
}

#content-2 {
  width: 100vw;
  height: 100vh;
  background-color: purple;
}

#content-3 {
  width: 100vw;
  height: 100vh;
  background-color: blue;
}

.page-name {
  position: fixed;
  z-index: 100;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: pink;
  transition: all 0.3s ease-in;
  padding: 0 200px;
  font-size: 40px;
}

.body-copy {
  position: relative;
  top: 50%;
  background-color: white;
  margin: 0 auto;
  text-align: center;
  width: 400px;
}

.fixed-header {
  position: fixed;
  z-index: 100;
  top: 10px;
  left: 50%;
  transform: translate(-50%, 0);
  background-color: pink;
  transition: all 0.3s ease-in;
  padding: 0 100px;
  font-size: 24px;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 04:27:01