CSSintermediate 7 min
Smooth changes between states, such as hover and focus, with the transition property.
How to animate the change between two states of an element using transition, plus the :hover and :focus states that trigger it.
Instant jumps feel harsh. A short, smooth change helps people notice that something responded to them, and makes an interface feel polished.
A transition tells the browser to animate between an old value and a new value instead of jumping. You set it on the element's normal state:
transition takes up to four values: the property to animate (or all), the duration (0.3s), a timing function (ease, linear, ease-in-out) and an optional delay.
Pseudo-classes such as :hover (mouse over), :focus (keyboard focus) and :active (while pressed) describe states that trigger the change.
Properties like transform and opacity animate smoothly and cheaply. For example transform: scale(1.1) grows an element and translateY(-4px) lifts it.
transition listing two properties with their durations..btn:hover sets a new background and moves the button up 4px.:focus-visible shows an outline for keyboard users only.Change the duration to 1s to see the effect clearly. Then add transform: scale(1.1) to the hover state.
transition only on :hover, so the change animates in but snaps back out. Put it on the normal state.width or top on large pages, which can be slow. Prefer transform and opacity.transition: property duration timing smooths a change.:hover and :focus.transform and opacity, and respect reduced motion.Next: placing elements exactly where you want them.
button {
background: royalblue;
transition: background 0.3s ease;
}
button:hover {
background: tomato;
}<style>
.btn {
background: royalblue;
color: white;
border: none;
padding: 12px 24px;
border-radius: 8px;
cursor: pointer;
transition: background 0.3s ease, transform 0.2s ease;
}
.btn:hover {
background: tomato;
transform: translateY(-4px);
}
.btn:focus-visible {
outline: 3px solid gold;
}
</style>
<button class="btn">Hover or tab to me</button>