Transition in media query doesn't work in both directions

Viewed 147

I'm a newbie in CSS transitions and trying to figure out how it works with media queries.

I create a basic example where a want my button to go up and back to center with a smooth transition but it only works in one way: not working when it goes back to center.

This is the real example, where is possible to play resizing the width of the result window with your mouse to see the problem: https://jsfiddle.net/hgaoe3zc/

And this is my CSS with the transition:

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;
  }
}

Any idea will be really appreciate it : )

1 Answers

You need to set position: absolute in both states.

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>

Related