Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Practical HTML and CSS

You're reading from   Practical HTML and CSS Elevate your internet presence by creating modern and high-performance websites for the web

Arrow left icon
Product type Paperback
Published in Nov 2024
Publisher Packt
ISBN-13 9781835080917
Length 492 pages
Edition 2nd Edition
Languages
Arrow right icon
Authors (3):
Arrow left icon
Brett Jephson Brett Jephson
Author Profile Icon Brett Jephson
Brett Jephson
Lewis Coulson Lewis Coulson
Author Profile Icon Lewis Coulson
Lewis Coulson
Ana Carolina Silveira Ana Carolina Silveira
Author Profile Icon Ana Carolina Silveira
Ana Carolina Silveira
Arrow right icon
View More author details
Toc

Table of Contents (20) Chapters Close

Preface 1. Part 1: Introducing HTML and CSS
2. Chapter 1: Introduction to HTML and CSS FREE CHAPTER 3. Chapter 2: Structure and Layout 4. Chapter 3: Text and Typography Styling 5. Part 2: Understanding Website Fundamentals
6. Chapter 4: Creating and Styling Forms 7. Chapter 5: Adding Animation to Web Pages 8. Chapter 6: Themes, Color, and Polishing Techniques 9. Part 3: Building for All
10. Chapter 7: Using CSS and HTML to Boost Performance 11. Chapter 8: Responsive Web Design and Media Queries 12. Chapter 9: Ensuring Accessibility in HTML and CSS 13. Part 4: Advanced Concepts
14. Chapter 10: SEO Essentials for Web Developers 15. Chapter 11: Preprocessors and Tooling for Efficient Development 16. Chapter 12: Strategies for Maintaining CSS Code 17. Chapter 13: The Future of HTML and CSS – Advancements and Trends 18. Index 19. Other Books You May Enjoy

The keyframes rule and CSS animation properties

Occasionally, enhancing user experience throughout their journey with our app necessitates incorporating more intricate animations. Therefore, let’s delve deeper into understanding animation properties and the @keyframes rule.

To create a CSS animation sequence, we style the element we want to animate with the animation property or its sub-properties. This allows us to configure the timing, duration, and other details of how the animation sequence should progress.

However, it’s important to note that this setup doesn’t directly influence the visual appearance of the animation, as that aspect is controlled by the @keyframes rule.

The following are CSS animation properties and their shorthands:

Property

Values accepted

Description

animation (shorthand)

Set of values

A shorthand for combining the transition properties into a single property.

animation-delay

Seconds or milliseconds

animation-direction

normal, reverse, alternate or alternate-reverse

Determines whether an animation should proceed in a forward direction, a backward direction, or alternate between playing the sequence forward and backward.

animation-duration

Seconds or milliseconds

Sets the length of time for an animation.

animation-fill-mode

none, forwards, backwards, both

Defines how a CSS animation applies styles to its target before and/or after its execution.

animation-iteration-count

infinite or number

(default: 1)

The number of times an animation should play before stopping.

animation-name

keyframe name

Specifies the names of one or more @keyframes animations to be applied to an element

animation-play-state

running or paused

Sets whether an animation is running or paused.

animation-timeline

none, auto, scroll(), view() or named

Specifies the timeline that is used to control the progress of a CSS animation. This timeline can be the default document timeline, a scroll-triggered timeline, a view-triggered timeline, or even a custom-named timeline.

animation-timing-function

cubic-bezier(n,n,n,n), ease, ease-in, ease-out, ease-in-out, linear, step-start or step-end

Determines the progression of an animation throughout each cycle’s duration.

Table 5.2 – The animation properties and its accepted values

The shorthand for CSS @keyframes animation includes properties in a specific order:

  1. Duration: Time taken for one animation cycle
  2. Easing function: Rate of change over time
  3. Delay: Time before animation starts
  4. Iteration count: Number of animation cycles
  5. Direction: Play direction (forward, backward, and alternate)
  6. Fill mode: Styling before/after animation
  7. Play state: Whether animation is running/paused
  8. Name: Identifier for the animation

Default values apply if any property is omitted, except for duration and name, which are required for the animation to function. Here’s an example of a @keyframes shorthand:

animation: 3s ease-in 1s 2 reverse both paused slidein;

The @keyframes rule dictates the visual behavior of an animated element at specific intervals throughout the animation sequence. In CSS, animations are timed through style configurations, with keyframes using percentages to denote their position within the sequence. At 0%, the animation begins, and at 100%, it reaches its conclusion.

These key moments can be referred to as from and to, respectively, and are optional. If these points are not explicitly defined, the browser defaults to using the computed attribute values for animation initiation and completion. An example of keyframes to animate the filter: blur property is as follows:

@keyframes blurAnimation {
  from {
    filter: blur(0px); /* No blur at the beginning */
  }
  to {
    filter: blur(10px); /* Blurred effect at the end */
  }
}

Using the preceding example, we’re applying the animation named blurAnimation to a div, using the CSS animation shorthand:

div {
  width: 200px;
  height: 200px;
  background-color: lightblue;
  animation: blurAnimation 2s ease-in-out
             infinite alternate;
}
Figure 5.14 – Keyframe blurAnimation applied to a div

Figure 5.14 – Keyframe blurAnimation applied to a div

Exercise #4 – loading spinner with keyframes

Let’s create a div featuring a loading spinner to indicate to our users that their request is currently being processed. This is a straightforward and frequently employed application of CSS animations, which, depending on the architecture of the application, minimizes performance degradation compared to .gif files or JavaScript animations.

Before we begin the exercise, please download the image asset from the following link: https://packt.link/ypVhx. Once downloaded, ensure to place the spinner.svg file in the same folder as the HTML file.

The HTML code will include a div to contain the spinner and an image element for the spinner itself:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,
        initial-scale=1.0">
  <title>Load Spinner</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="container">
    <img src="./spinner.svg" alt="">
  </div>
</body>
</html>

Now, let’s create a file named style.css in the same folder as the HTML file. The initial styles for the elements are as follows:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
img {
  width: 50px;
  height: 50px;
}

When you open the HTML file in your browser, you’ll see a static image displayed:

Figure 5.15 – Static load spinner image

Figure 5.15 – Static load spinner image

Now, let’s create the animation using keyframes. The transform property is utilized to alter the appearance or position of a block element. In the upcoming keyframe, we’ll employ transform: rotate(360deg) to make the image spin in a full circle and ensure its animation concludes at the same point where it started:

@keyframes loadSpinner {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

Finally, we apply the loadSpinner animation to the img tag in CSS:

img {
  width: 50px;
  height: 50px;
  animation: loadSpinner 1s linear infinite;
}
Figure 5.16 – Visual representation of the spinner animation

Figure 5.16 – Visual representation of the spinner animation

The code containing the resolution for this exercise is accessible in the link provided here: https://packt.link/tbpEJ

Exercise #5 – menu icon shaking effect with keyframes

Let’s enhance the user experience by adding a dynamic shaking effect to the menu icons from Exercise #2. Navigate to the directory of the Exercise #2 project and follow these steps to implement the animation:

  1. Create keyframes: Define a keyframe animation named shake to bring life to the menu icons. This animation will add a subtle yet engaging shaking motion to the icons when hovered over:
    @keyframes shake {
      0% { transform: translateX(0); }
      25% { transform: translateX(-5px) rotate(5deg); }
      50% { transform: translateX(5px) rotate(-5deg); }
      75% { transform: translateX(-5px) rotate(5deg); }
      100% { transform: translateX(0); }
    }
  2. Apply animation: Assign the shake animation to the menu icons’ hover state. This ensures that the animation activates whenever a user interacts with the icons:
    ul li:hover a img {
      width: 24px;
      height: 24px;
      animation: shake 0.4s ease;
    }

By following these steps, you’ll add an interactive touch to the menu icons, making the user experience more engaging and visually appealing:

Figure 5.17 – Visual representation of the menu animation flow

Figure 5.17 – Visual representation of the menu animation flow

The code containing the resolution for this exercise is accessible in the link provided here: https://packt.link/36avH

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image