HTML/CSS - 17

HTML/CSS - 17: Transitions, Animations & Hover Effects

CSS can do more than change how a page looks. It can also create smooth movement and simple animations that respond to the visitor.

A transition makes a change happen gradually instead of instantly. The transform property can move, rotate, or resize an element. For repeating or more detailed movement, CSS uses @keyframes.

Your challenge: Create a box that changes smoothly when you hover over it, then add a simple animation using @keyframes.

✦ HTML Editor
▶ Live Output

What should you notice?

Without a transition, a hover effect changes immediately. With a rule such as transition: all 0.4s ease;, the browser smoothly moves between the normal style and the hover style.

Try transform: The transform property can visually change an element without rewriting its HTML.

For example: transform: scale(1.1); makes an element appear slightly larger.

You can also use: transform: rotate(5deg); to rotate it.

Several transformations can be combined: transform: scale(1.1) rotate(5deg);

Experiment: Change the transition duration from 0.4s to 1s. Then try 0.1s. Notice how the same effect can feel very different depending on its speed.

What are keyframes? A @keyframes rule describes different stages of an animation.

For example, a bounce animation can start at its normal position, move upward halfway through, and then return to where it started.

The percentages describe points in the animation: 0% is the beginning, 50% is halfway, and 100% is the end.

Try the animation: After creating the bounce keyframes, add this to the box: animation: bounce 1s infinite;

The first value is the animation name, 1s is the duration, and infinite tells it to repeat continuously.

Experiment: Change infinite to 3. The animation should run three times and then stop.

Good animation habit: Motion is usually most effective when it helps communicate something. Small hover effects can show that an element is interactive, while constant movement everywhere can become distracting.

It is also a good idea to avoid large or rapid animations when a simpler effect can do the same job.

👀 Show Solution
<style>

  .animated-box {
    display: inline-block;
    background-color: #111;
    border: 3px solid #8A8A8A;
    padding: 40px 60px;
    border-radius: 12px;
    transition: all 0.4s ease;
  }

  .animated-box:hover {
    transform: scale(1.1) rotate(5deg);
    background-color: #8A8A8A;
    color: #000;
  }

  @keyframes bounce {

    0% {
      transform: translateY(0);
    }

    50% {
      transform: translateY(-20px);
    }

    100% {
      transform: translateY(0);
    }

  }

</style>

The transition makes the hover change smooth. The :hover rule uses transform to resize and rotate the box, while @keyframes defines a separate animation that can be applied when needed.