Learn to enhance your webpage with CSS transitions, hover effects, keyframes and pseudo-elements to add motion and interactivity without JavaScript.
Frontend Development Month 1: HTML, CSS & Tailwind12 min readFree
Webbo3 Frontend Development · Month 1 · Lesson 15
Transitions, Animations and Pseudo-classes
Learn to enhance your webpage with CSS transitions, hover effects, keyframes and pseudo-elements to add motion and interactivity without JavaScript.
You've built a few web pages now, and they look good, but they're a bit static. When you interact with a website, you expect things to happen - buttons to change color when you hover over them, images to fade in when they load, and menus to slide out when you click on them. Right now, you might be thinking that to achieve these effects, you need to learn JavaScript, but that's not the case. With just HTML and CSS, you can add motion and interactivity to your web pages.
By the end of this lesson, you'll be able to create web pages that respond to user interactions without writing a single line of JavaScript. You'll learn how to use CSS transitions to smoothly change the properties of an element over time, and how to use CSS animations to create more complex effects. You'll also learn about pseudo-classes, which allow you to apply different styles to an element based on its state - for example, when it's being hovered over or when it's been visited. These techniques will allow you to create web pages that are more engaging and interactive, without having to learn a new programming language.
This is a powerful set of skills to have, and it will take your web pages to the next level. You'll be able to create buttons that change color when you hover over them, images that fade in when they load, and menus that slide out when you click on them. You'll be able to create web pages that feel more dynamic and responsive, and that will make a better impression on your users. And the best part is, you'll be able to do all of this using just HTML and CSS, without having to learn any JavaScript.
What you need before starting
Everything from the previous lesson, and the project folder you have been building in. Work along in your own editor as you read — this lesson is written to be typed, not skimmed.
Pseudo-classes: :hover, :focus and :active
Why Pseudo-classes Matter
Pseudo-classes are used to apply styles to elements based on their state. For example, the :hover pseudo-class applies styles when the mouse is over an element. The :focus pseudo-class applies styles when an element has keyboard focus, which is crucial for users who rely on their keyboard to navigate the web. Without :focus styles, it can be difficult for these users to determine which element currently has focus.
:hover, :focus and :active in Practice
Here is an example of how to use these pseudo-classes:
" sandbox="allow-same-origin" loading="lazy" title="Live result of the code above">
In this example, the button's background color changes when you hover over it, and a blue box shadow appears when it has keyboard focus. The background color also changes when the button is active (i.e., being clicked).
A common mistake beginners make is forgetting to include the :focus pseudo-class, which can make their website inaccessible to keyboard users. To spot this mistake, check if your interactive elements (like buttons and links) have a visible focus state when you navigate to them using your keyboard.
Transitions and Animations with @keyframes
Building a Simple Loading Spinner
The @keyframes rule is used to define animations. Here is an example of how to use it to build a simple loading spinner:
" sandbox="allow-same-origin" loading="lazy" title="Live result of the code above">
In this example, the @keyframes rule defines an animation called "spin" that rotates an element 360 degrees. The .spinner class applies this animation to an element, creating a simple loading spinner.
Fade-in Animation
You can also use @keyframes to create a fade-in animation:
" sandbox="allow-same-origin" loading="lazy" title="Live result of the code above">
In this example, the @keyframes rule defines an animation called "fadeIn" that changes an element's opacity from 0 to 1 over time. The .fadeIn class applies this animation to an element, making it fade in when the page loads.
A common mistake beginners make is forgetting to specify the animation duration, which can cause the animation to not run at all. To spot this mistake, check if your animation has a duration specified (e.g., 2s in the example above).
Pseudo-elements: Tooltips and Custom Underlines
Building a Tooltip
Pseudo-elements can be used to add content to an element without modifying its HTML. Here is an example of how to use a pseudo-element to build a tooltip:
In this example, the ::after pseudo-element is used to add a tooltip to an element. The tooltip is hidden by default, but becomes visible when the element is hovered over.
Custom Underline
You can also use pseudo-elements to create a custom underline:
In this example, the ::after pseudo-element is used to add a custom underline to an element. The underline is a simple 2-pixel high rectangle that spans the full width of the element.
A common mistake beginners make is using the wrong pseudo-element (e.g., using ::before instead of ::after). To spot this mistake, check the CSS specification for the pseudo-element you are trying to use, and make sure you are using it correctly.
Transitions
The Transition Property
The transition property is a shorthand way to set the transition effect for an element. It has four parts: property, duration, timing-function, and delay. Understanding each part is crucial for creating smooth transitions. The property specifies which CSS property you want to add a transition effect to, such as width, height, or background-color. The duration sets how long the transition effect will take, usually in seconds (s) or milliseconds (ms). The timing-function determines the speed of the transition, and the delay sets when the transition will start.
Example of a Transition
For example, if you want to add a transition effect to a button when you hover over it, you can use the following code:
" sandbox="allow-same-origin" loading="lazy" title="Live result of the code above">
In this code, the transition property is set to change the background-color of the button over a duration of 0.5 seconds, with a timing-function of ease-in-out, and no delay. When you hover over the button, the background-color changes to #4CAF50.
Animation Timing Functions
Understanding Timing Functions
Animation timing functions, also known as easing functions, determine how the transition effect will progress over time. In plain language, it's like controlling the speed of the transition. For example, the linear timing function will move at a constant speed, while the ease-in timing function will start slowly and speed up. The ease-out timing function will start quickly and slow down, and the ease-in-out timing function will start slowly, speed up, and then slow down.
Common Mistake with Timing Functions
A common mistake beginners make is using the wrong timing function for their transition. For example, using a linear timing function for a button hover effect can make it feel robotic. To spot this mistake, pay attention to how the transition feels. If it feels unnatural or abrupt, you may need to adjust the timing function.
Prefers-Reduced-Motion
What is Prefers-Reduced-Motion?
The prefers-reduced-motion media query is used to detect if the user has requested that the system minimize the amount of motion it uses. This is usually done to help users with vestibular disorders or other conditions that make it difficult to view motion.
Why Respecting it is Not Optional
Respecting the prefers-reduced-motion media query is not optional because it's a matter of accessibility. Not respecting it can make your website unusable for some users. To respect it, you can add the following code to your CSS:
In this code, if the user has requested reduced motion, all animations and transitions will be turned off. This ensures that your website is accessible to all users, regardless of their needs.
Example of Respecting Prefers-Reduced-Motion
You can also use the prefers-reduced-motion media query to reduce the motion of specific elements, rather than turning off all animations and transitions. For example:
" sandbox="allow-same-origin" loading="lazy" title="Live result of the code above">
In this code, if the user has requested reduced motion, the transition effect on the button will be removed, making it more accessible.
Properties for Animations
Cheap Properties to Animate
When creating animations, it's essential to choose properties that don't cause the browser to work too hard. Properties like opacity, transform, and scale are considered "cheap" to animate because they don't require the browser to recalculate the layout of the page. This makes them ideal for smooth animations.
Properties that Cause Jank
On the other hand, properties like width, height, padding, and margin can cause jank (stuttering or lag) when animated. This is because the browser needs to recalculate the layout of the page every time these properties change, which can be time-consuming. Beginners often make the mistake of animating these properties without realizing the performance impact. To spot this mistake, look for animations that stutter or lag, and check if the animated properties are layout-related.
Pseudo-classes
::before and ::after
Pseudo-classes like ::before and ::after allow you to add content to an element without modifying the HTML. These pseudo-classes are used to create visual effects or add icons to an element.
The Content Property
The content property is used in conjunction with ::before and ::after to specify the content to be added. For example, you can use the content property to add a quote mark before a blockquote element.
CSSExample and result
blockquote {position: relative;
padding: 20px;
background-color: #f0f0f0;
}
5{content: ";\201C"; /* adds a left double quote mark */position: absolute;
top: 10px;
left: 10px;
font-size: 30px;
color: #666;
}
12{content: ";\201D"; /* adds a right double quote mark */position: absolute;
bottom: 10px;
right: 10px;
font-size: 30px;
color: #666;
}
Result
In this example, the ::before pseudo-class is used to add a left double quote mark before the blockquote element, and the ::after pseudo-class is used to add a right double quote mark after the blockquote element. The content property is used to specify the quote marks to be added. A common mistake beginners make is forgetting to include the content property when using ::before or ::after, which means the pseudo-element will not be visible. To spot this mistake, check if the pseudo-element is not appearing as expected, and verify that the content property is present.
Do this now
To apply transitions, animations and pseudo-classes to your webpage, follow these steps. This exercise should take you around 20-30 minutes, depending on how familiar you are with CSS.
Open your webpage's stylesheet (usually named style.css) in a text editor.
Add a CSS rule to target all button elements on your page, and include a transition effect that changes the background color when you hover over the button.
Target all card elements on your page and add a similar transition effect.
Define a keyframe animation that changes the opacity of an element from 0 to 1 over a period of 2 seconds.
Apply this animation to at least one element on your page.
Use the ::after pseudo-element to add a decorative underline to a heading element on your page.
Save your changes and refresh your webpage to see the effects.
Remember to be patient and take your time, as CSS can be tricky to work with, especially when dealing with transitions and animations. Common mistakes to watch out for include forgetting to add the transition property, misspelling CSS property names, and not defining the keyframe animation correctly.
How to know you got it right
Check the following to ensure you have completed the exercise correctly:
When you hover over a button, its background color changes smoothly over a short period of time.
When you hover over a card, its background color or other properties also change smoothly.
An element on your page fades in over a period of 2 seconds when the page loads.
A heading element on your page has a decorative underline that is added using the ::after pseudo-element.
Common mistakes
Beginners often make the following mistakes when working with transitions, animations, and pseudo-classes:
Forgetting to specify the duration of a transition, resulting in a default duration of 0s, which makes the transition instantaneous. This happens because the duration is not explicitly set, and the fix is to add a duration, for example, transition: background-color 1s;
Using the :hover pseudo-class on a parent element and expecting it to affect the child elements, when in fact it only affects the parent. This occurs due to a lack of understanding of CSS specificity, and the fix is to use the :hover pseudo-class on the child elements or use a more specific selector.
Defining an animation but not specifying the animation-name property, which means the animation will not be applied. This mistake happens because the animation is defined but not referenced, and the fix is to add the animation-name property, for example, animation-name: myanimation;
Not using the fill-mode property to control the state of an element before or after an animation, resulting in unexpected behavior. This error occurs because the default fill-mode is none, and the fix is to set the fill-mode to forwards or backwards to maintain the final state of the animation.
Questions students ask
Here are some common questions students ask when learning about transitions, animations, and pseudo-classes:
What is the difference between a transition and an animation?
Transitions are used for simple state changes, while animations are used for more complex effects.
Can I use multiple pseudo-classes on the same element?
Yes, you can use multiple pseudo-classes, such as :hover and :active, on the same element.
How do I make an animation run only once?
You can use the animation-iteration-count property and set it to 1 to make the animation run only once.
Quick recap: Pseudo-classes: :hover, :focus and :active · Transitions and Animations with @keyframes · Pseudo-elements: Tooltips and Custom Underlines · Transitions · Animation Timing Functions · Prefers-Reduced-Motion · Properties for Animations · Pseudo-classes
Next lesson: CSS Variables and Debugging With DevTools.
Learn this with a real instructor
Free lessons take you a long way on your own. The full programmes add live classes,
assignments, Skill Points and a certificate — built for African students.