媒体查询中的转换在两个方向上都不起作用

Transition in media query doesn't work in both directions

我是 CSS 转换的新手,正在尝试弄清楚它如何与媒体查询一起工作。

我创建了一个基本示例,希望我的按钮可以平稳过渡向上和返回中心,但它只能以一种方式工作:回到中心时不起作用。

这是真实的例子,可以用鼠标玩调整结果的宽度window来查看问题: https://jsfiddle.net/hgaoe3zc/

这是我的 CSS 转换:

body {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

button {
  top: calc(50% - 30px);
  transition: top 0.5s ease-in-out;
}

@media only screen and (max-width: 500px) {
  button {
    position: absolute;
    top: 6rem;
  }
}

任何想法都会非常感激:)

您需要在两种状态下都设置position: absolute

https://jsfiddle.net/yo4fedq6/

body {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

button {
  top: calc(50% - 30px);
  position: absolute; // HERE
  transition: top 0.5s ease-in-out;
}

@media only screen and (max-width: 500px) {
  button {
    top: 6rem;
  }
}
<button>Button</button>