The garden’s Sign up button and nav links switch colors the instant a visitor points at them. This lesson makes those changes fade, and shows why the transition belongs on the element’s own rule rather than in the hover rule.
Key Points
- A transition tells the browser to animate a property’s change over time instead of switching it at once. You give it the property to watch and how long the change takes:
transition: background-color 1s;. - Watch out: with the transition in the
form button:hoverrule, next to the new color, the Sign up button fades to dark green on the way in and snaps straight back to green on the way out. - Why: each time a property changes, the browser uses the transition of the rules that match the element once the pointer has arrived or left, in the new state. When the pointer arrives, the hover rule matches, so its transition applies. When the pointer leaves, the hover rule stops matching, and its transition goes with it. The button’s own rule has none, so the color switches at once.
- States, not events: if you thought of hover as an event with the transition attached to it, CSS doesn’t work that way. It matches states, and once the pointer leaves, the hover state is gone, transition and all.
- The fix: put the transition on the element’s own rule, here
button, which matches in both states, and keep only the new values in the state rule. Then the change fades both ways. - The four parts this lesson uses: the property, the duration, the timing function, and the delay.
- The default timing function,
ease, does most of the change early, then slows into the new color. Half a second into a one-second fade, the button is already about four fifths of the way to dark green.linearmoves at an even speed, so it’s halfway there at halfway:background-color 1s linear. - A delay, such as
0.5s, makes the button wait before it fades, on the way in and on the way back. Of the two times, the first is always the duration, the other the delay:background-color 1s ease 0.5s. - For the site: one second is long enough to watch but slow for a button you click, so the button and the nav links use
0.3swith the defaultease, which you don’t need to write. The nav links’ hover and focus rule changes two properties, so the links’ own rule,ainside.site-nav, lists both, one transition per property, separated by a comma. - Nav links: they fade as the pointer passes and as you reach them with Tab. The focus ring still appears at once, because only the background and text colors have a transition.
- Watch out: if you give an answer in the FAQ a height transition from
0toauto, it still jumps open. Withtransitionalone, the browser can’t step between a length andauto. A smooth opening needs techniques beyond this course. - The rule: put
transitionon the element’s own rule, and keep only the new values in the state rule.
Final Code
In the components layer of style.css, the button rule gets the transition, and the new hover rule keeps only the new color: