jiyoon
jiyoon

Reputation: 231

Why is my React Button transition not working?

I'm using styled components in a React App to animate a button to move upwards 5px on hover. It does move up but the transition is not smooth. Does anyone know how to fix this?

CSS:

const UpButton = styled.button`
  font-family: "Avenir";
  height: 3em;
  width: 3em;;
  color: white;
  border: 2px solid white;
  background: #1d1d20;
  font-size: 1em;
  position: relative;
  float: right;

  &:hover{
    top: -5px;
    cursor: pointer;
  }
`

Upvotes: 1

Views: 689

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

This is a common problem with using transition. Add the following to the normal state and also your code is missing a transition property:

transition: all 0.5s linear;
top: 0;

So that, the CSS will know to animate between 0px and -5px.

Your full code should be:

const UpButton = styled.button`
  font-family: "Avenir";
  height: 3em;
  width: 3em;;
  color: white;
  border: 2px solid white;
  background: #1d1d20;
  font-size: 1em;
  position: relative;
  float: right;
  transition: all 0.5s linear;
  top: 0;
  &:hover{
    top: -5px;
    cursor: pointer;
  }
`;

You can see the working and difference here:

button {
  height: 3em;
  width: 3em;
  color: white;
  border: 2px solid white;
  background: #1d1d20;
  font-size: 1em;
  position: relative;
  float: left;
  transition: all 0.5s linear;
}
button.top {
  top: 0;
}
button.top:hover,
button:hover {
  top: -5px;
  cursor: pointer;
}
<button>No top</button>
<br /><br /><br />
<button class="top">With top</button>

Upvotes: 1

Related Questions