Using CSS transitions - CSS: Cascading Style Sheets | MDN (2024)

CSS transitions provide a way to control animation speed when changing CSS properties. Instead of having property changes take effect immediately, you can cause the changes in a property to take place over a period of time. For example, if you change the color of an element from white to black, usually the change is instantaneous. With CSS transitions enabled, changes occur at time intervals that follow an acceleration curve, all of which can be customized.

Animations that involve transitioning between two states are often called implicit transitions as the states in between the start and final states are implicitly defined by the browser.

Using CSS transitions - CSS: Cascading Style Sheets | MDN (1)

CSS transitions let you decide which properties to animate (by listing them explicitly), when the animation will start (by setting a delay), how long the transition will last (by setting a duration), and how the transition will run (by defining an easing function, e.g., linearly or quick at the beginning, slow at the end).

Which CSS properties can be transitioned?

The Web author can define which property has to be animated and in which way. This allows the creation of complex transitions. However, some properties are not animatable as it doesn't make sense to animate them.

Note: The auto value is often a very complex case. The specification recommends not animating from and to auto. Some user agents, like those based on Gecko, implement this requirement and others, like those based on WebKit, are less strict. Using animations with auto may lead to unpredictable results, depending on the browser and its version, and should be avoided.

Defining transitions

CSS Transitions are controlled using the shorthand transition property. This is the best way to configure transitions, as it makes it easier to avoid out of sync parameters, which can be very frustrating to have to spend lots of time debugging in CSS.

You can control the individual components of the transition with the following sub-properties:

transition-property

Specifies the name or names of the CSS properties to which transitions should be applied. Only properties listed here are animated during transitions; changes to all other properties occur instantaneously as usual.

transition-duration

Specifies the duration over which transitions should occur. You can specify a single duration that applies to all properties during the transition, or multiple values to allow each property to transition over a different period of time.

transition-timing-function

Specifies a function to define how intermediate values for properties are computed. Easing functions determine how intermediate values of the transition are calculated. Most easing functions can be specified by providing the graph of the corresponding function, as defined by four points defining a cubic bezier. You can also choose easing from Easing functions cheat sheet.

transition-delay

Defines how long to wait between the time a property is changed and the transition actually begins.

The transition shorthand CSS syntax is written as follows:

css

div { transition: <property> <duration> <timing-function> <delay>;}

Examples

Basic example

This example performs a four-second font size transition with a two-second delay between the time the user mouses over the element and the beginning of the animation effect:

css

#delay { font-size: 14px; transition-property: font-size; transition-duration: 4s; transition-delay: 2s;}#delay:hover { font-size: 36px;}

Multiple animated properties example

<body> <p> The box below combines transitions for: width, height, background-color, rotate. Hover over the box to see these properties animated. </p> <div class="box">Sample</div></body>

CSS

css

.box { border-style: solid; border-width: 1px; display: block; width: 100px; height: 100px; background-color: #0000ff; transition: width 2s, height 2s, background-color 2s, rotate 2s;}.box:hover { background-color: #ffcccc; width: 200px; height: 200px; rotate: 180deg;}

When property value lists are of different lengths

If any property's list of values is shorter than the others, its values are repeated to make them match. For example:

css

div { transition-property: opacity, left, top, height; transition-duration: 3s, 5s;}

This is treated as if it were:

css

div { transition-property: opacity, left, top, height; transition-duration: 3s, 5s, 3s, 5s;}

Similarly, if any property's value list is longer than that for transition-property, it's truncated, so if you have the following CSS:

css

div { transition-property: opacity, left; transition-duration: 3s, 5s, 2s, 1s;}

This gets interpreted as:

css

div { transition-property: opacity, left; transition-duration: 3s, 5s;}

Using transitions when highlighting menus

A common use of CSS is to highlight items in a menu as the user hovers the mouse cursor over them. It's easy to use transitions to make the effect even more attractive.

First, we set up the menu using HTML:

html

<nav> <a href="#">Home</a> <a href="#">About</a> <a href="#">Contact Us</a> <a href="#">Links</a></nav>

Then we build the CSS to implement the look and feel of our menu:

css

nav { display: flex; gap: 0.5rem;}a { flex: 1; background-color: #333; color: #fff; border: 1px solid; padding: 0.5rem; text-align: center; text-decoration: none; transition: all 0.5s ease-out;}a:hover,a:focus { background-color: #fff; color: #333;}

This CSS establishes the look of the menu, with the background and text colors both changing when the element is in its :hover and :focus states:

Transitioning display and content-visibility

This example demonstrates how display and content-visibility can be transitioned. This behavior is useful for creating entry/exit animations where you want to for example remove a container from the DOM with display: none, but have it fade out with opacity rather than disappearing immediately.

Supporting browsers transition display and content-visibility with a variation on the discrete animation type. This generally means that properties will flip between two values 50% through animating between the two.

There is an exception, however, which is when animating to/from display: none or content-visibility: hidden. In this case, the browser will flip between the two values so that the transitioned content is shown for the entire animation duration.

So for example:

  • When animating display from none to block (or another visible display value), the value will flip to block at 0% of the animation duration so it is visible throughout.
  • When animating display from block (or another visible display value) to none, the value will flip to none at 100% of the animation duration so it is visible throughout.

When transitioning these properties transition-behavior: allow-discrete needs to be set on the transitions. This effectively enables display/content-visibility transitions.

When transitioning display, @starting-style is needed to provide a set of starting values for properties set on an element that you want to transition from when the element receives its first style update. This is needed to avoid unexpected behavior. By default, CSS transitions are not triggered on elements' first style updates when they first appear in the DOM, which includes when display changes from none to another state. content-visibility animations do not need starting values specified in a @starting-style block. This is because content-visibility doesn't hide an element from the DOM like display does: it just skips rendering the element's content.

HTML

The HTML contains two <p> elements with a <div> in between that we will animate from display none to block.

html

<p> Click anywhere on the screen or press any key to toggle the <code>&lt;div&gt;</code> between hidden and showing.</p><div> This is a <code>&lt;div&gt;</code> element that transitions between <code>display: none; opacity: 0</code> and <code>display: block; opacity: 1</code>. Neat, huh?</div><p> This is another paragraph to show that <code>display: none; </code> is being applied and removed on the above <code>&lt;div&gt; </code>. If only its <code>opacity</code> was being changed, it would always take up the space in the DOM.</p>

CSS

css

html { height: 100vh;}div { font-size: 1.6rem; padding: 20px; border: 3px solid red; border-radius: 20px; width: 480px; display: none; opacity: 0; transition: opacity 1s, display 1s allow-discrete; /* Equivalent to transition: all 1s allow-discrete; */}.showing { opacity: 1; display: block;}@starting-style { .showing { opacity: 0; }}

Note the @starting-style block used to specify the starting style for the transition, and the inclusion of the display property in the transitions list, with allow-discrete set on it.

JavaScript

Finally, we include a bit of JavaScript to set up event listeners to trigger the transition (via the showing class).

js

const divElem = document.querySelector("div");const htmlElem = document.querySelector(":root");htmlElem.addEventListener("click", showHide);document.addEventListener("keydown", showHide);function showHide() { divElem.classList.toggle("showing");}

Result

The code renders as follows:

JavaScript examples

Note: Care should be taken when using a transition immediately after:

  • adding the element to the DOM using .appendChild()
  • removing an element's display: none; property.

This is treated as if the initial state had never occurred and the element was always in its final state. The easy way to overcome this limitation is to apply a setTimeout() of a handful of milliseconds before changing the CSS property you intend to transition to.

Using transitions to make JavaScript functionality smooth

Transitions are a great tool to make things look much smoother without having to do anything to your JavaScript functionality. Take the following example.

html

<p>Click anywhere to move the ball</p><div id="foo" class="ball"></div>

Using JavaScript you can make the effect of moving the ball to a certain position happen:

js

const f = document.getElementById("foo");document.addEventListener( "click", (ev) => { f.style.transform = `translateY(${ev.clientY - 25}px)`; f.style.transform += `translateX(${ev.clientX - 25}px)`; }, false,);

With CSS you can make it smooth without any extra effort. Add a transition to the element and any change will happen smoothly:

css

.ball { border-radius: 25px; width: 50px; height: 50px; background: #c00; position: absolute; top: 0; left: 0; transition: transform 1s;}

Detecting the start and completion of a transition

You can use the transitionend event to detect that an animation has finished running. This is a TransitionEvent object, which has two added properties beyond a typical Event object:

propertyName

A string indicating the name of the CSS property whose transition completed.

elapsedTime

A float indicating the number of seconds the transition had been running at the time the event fired. This value isn't affected by the value of transition-delay.

As usual, you can use the addEventListener() method to monitor for this event:

js

el.addEventListener("transitionend", updateTransition, true);

You detect the beginning of a transition using transitionrun (fires before any delay) and transitionstart (fires after any delay), in the same kind of fashion:

js

el.addEventListener("transitionrun", signalStart, true);el.addEventListener("transitionstart", signalStart, true);

Note: The transitionend event doesn't fire if the transition is aborted before the transition is completed because either the element is made display: none or the animating property's value is changed.

Specifications

Specification
CSS Transitions

See also

  • The TransitionEvent interface and the transitionend event
  • Using CSS animations
Using CSS transitions - CSS: Cascading Style Sheets | MDN (2024)

FAQs

What are CSS transitions best used for? ›

CSS transitions allows you to change property values smoothly, over a given duration. In this chapter you will learn about the following properties: transition. transition-delay.

How can I use transition in CSS? ›

Use the transition-timing-function property to vary the speed of a CSS transition over the course of the transition-duration . By default, CSS will transition your elements at a constant speed ( transition-timing-function: linear ).

What is the CSS transition property used for? ›

CSS transitions provide a way to control animation speed when changing CSS properties. Instead of having property changes take effect immediately, you can cause the changes in a property to take place over a period of time.

What is the key difference between CSS transitions and CSS animations? ›

Unlike a transition, which only plays through once after it's been triggered, a CSS animation doesn't require a triggering action and can be set to loop. You can make it repeat as many times as you want or set it to go on forever.

What is CSS best used for? ›

CSS (Cascading Style Sheets) is used to style and layout web pages — for example, to alter the font, color, size, and spacing of your content, split it into multiple columns, or add animations and other decorative features.

When should you use CSS? ›

A website can run without CSS, but it certainly isn't pretty. CSS makes the front-end of a website shine and it creates a great user experience. Without CSS, websites would be less pleasing to the eye and likely much harder to navigate. In addition to layout and format, CSS is responsible for font color and more.

How to transition text in CSS? ›

Fade-in Text Transition Using CSS
  1. In your HTML, create a div with the class fade-in-text.
  2. Place your text inside this div. ...
  3. In your CSS, give the fade-in-text class the declaration animation: fadeIn 5s. ...
  4. Use the @keyframes rule paired with fadeIn. ...
  5. Add vendor prefixes for cross-browser compatibility.
Apr 3, 2024

What is the alternative to transitions in CSS? ›

CSS Animations are a more powerful alternative to transitions. Rather than rely on a change from one beginning state to an end state, animations can be made up of as many in-between states as you like, and offer more control over how the states are animated.

How to make color transition in CSS? ›

To use transition to change color, you'll need to specify the CSS properties transition and background-color . This code will make the background color of the div element transition from blue to red over 1 second when hovered over. You can learn more about CSS transitions here.

How many transition properties are there in CSS? ›

The transition property is a shorthand of four CSS properties, transition-property , transition-duration , transition-timing-function , transition-delay . transition-property refers to the CSS property you wish to transition.

What is CSS style property? ›

A CSS property determines an HTML element's style or behavior. Examples include font style, transform, border, color, and margin. A CSS property declaration consists of a property name and a property value. Following a colon, the value is listed after the property name.

Which property most use CSS? ›

In CSS, some of the most common properties for styling HTML elements are:
  • color : Used to set the text color.
  • font-size : Used to set the size of the font.
  • background-color : Used to set the background color.
  • margin : Used to create space around an element.
  • padding : Used to create space within an element.

What is CSS animation used for? ›

What are CSS Animations? An animation lets an element gradually change from one style to another. You can change as many CSS properties you want, as many times as you want. To use CSS animation, you must first specify some keyframes for the animation.

What are the two components of CSS animations? ›

Animations consist of two components: a style describing the CSS animation and a set of keyframes that indicate the start and end states of the animation's style, as well as possible intermediate waypoints.

What is the steps function in CSS? ›

steps() is a timing function that allows us to break an animation or transition into segments, rather than one continuous transition from one state to another. The function takes two parameters — the first specifies the positive number of steps we want our animation to take.

When and why should we use transitions animations? ›

Animations and transitions can make your presentations more energetic and fluid. But don't overwhelm your audience: using 1-2 different styles per presentation is a good best practice.

Are CSS animations useful? ›

There are three key advantages to CSS animations over traditional script-driven animation techniques: They're easy to use for simple animations; you can create them without even having to know JavaScript. The animations run well, even under moderate system load. Simple animations can often perform poorly in JavaScript.

What is the purpose of CSS transform? ›

Definition and Usage

The transform property applies a 2D or 3D transformation to an element. This property allows you to rotate, scale, move, skew, etc., elements.

Are page transitions good? ›

👉 Scroll transitions are a safe option: Not only do they enhance the visual experience and make your website more dynamic and exciting, but they load gradually and asynchronously, not compromising the page speed.

References

Top Articles
Dimensional Doors - Feed The Beast Wiki
Dimensional Doors - Minecraft Mod
Pollen Count Los Altos
Bild Poster Ikea
Www.1Tamilmv.cafe
Best Big Jumpshot 2K23
How To Do A Springboard Attack In Wwe 2K22
What Are the Best Cal State Schools? | BestColleges
Sam's Club Gas Price Hilliard
Songkick Detroit
Evita Role Wsj Crossword Clue
Daniela Antury Telegram
How Many Slices Are In A Large Pizza? | Number Of Pizzas To Order For Your Next Party
Jack Daniels Pop Tarts
Job Shop Hearthside Schedule
How to find cash from balance sheet?
Powerball winning numbers for Saturday, Sept. 14. Check tickets for $152 million drawing
Inter-Tech IM-2 Expander/SAMA IM01 Pro
Craigslist Sparta Nj
FDA Approves Arcutis’ ZORYVE® (roflumilast) Topical Foam, 0.3% for the Treatment of Seborrheic Dermatitis in Individuals Aged 9 Years and Older - Arcutis Biotherapeutics
Like Some Annoyed Drivers Wsj Crossword
Village
Panola County Busted Newspaper
Boise Craigslist Cars And Trucks - By Owner
Hesburgh Library Catalog
Water Temperature Robert Moses
Publix Near 12401 International Drive
Cfv Mychart
Ordensfrau: Der Tod ist die Geburt in ein Leben bei Gott
Winterset Rants And Raves
Craigslist Sf Garage Sales
Lincoln Financial Field, section 110, row 4, home of Philadelphia Eagles, Temple Owls, page 1
Street Fighter 6 Nexus
Transformers Movie Wiki
Roadtoutopiasweepstakes.con
Steven Batash Md Pc Photos
Strange World Showtimes Near Atlas Cinemas Great Lakes Stadium 16
Main Street Station Coshocton Menu
Empires And Puzzles Dark Chest
Überblick zum Barotrauma - Überblick zum Barotrauma - MSD Manual Profi-Ausgabe
Section 212 at MetLife Stadium
Reese Witherspoon Wiki
Lcwc 911 Live Incident List Live Status
At Home Hourly Pay
Courtney Roberson Rob Dyrdek
Todd Gutner Salary
Www Craigslist Com Atlanta Ga
Arch Aplin Iii Felony
Sky Dental Cartersville
Diamond Desires Nyc
Nkey rollover - Hitta bästa priset på Prisjakt
Latest Posts
Article information

Author: Zonia Mosciski DO

Last Updated:

Views: 5807

Rating: 4 / 5 (51 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Zonia Mosciski DO

Birthday: 1996-05-16

Address: Suite 228 919 Deana Ford, Lake Meridithberg, NE 60017-4257

Phone: +2613987384138

Job: Chief Retail Officer

Hobby: Tai chi, Dowsing, Poi, Letterboxing, Watching movies, Video gaming, Singing

Introduction: My name is Zonia Mosciski DO, I am a enchanting, joyous, lovely, successful, hilarious, tender, outstanding person who loves writing and wants to share my knowledge and understanding with you.