Loading...
The Essential Guide to Animating SVGs with CSS

The Essential Guide to Animating SVGs with CSS

Animation enhances user experience by adding visual interest and interactivity to websites. It can capture users' attention, guide them through the website, and communicate information effectively. With SVG, web designers can create smooth, responsive animations that load quickly and adapt to different screen sizes. This allows for a more engaging and dynamic user experience, ultimately improving the overall usability and enjoyment of the website.

This article will discuss the reasons and advantages of using CSS to animate SVGs. Web designers can produce engaging and interactive visuals that elevate the user experience using CSS animations. We will examine the different methods and properties involved in CSS animations to animate SVGs and provide readers with clear instructions and examples to follow along with.

What is SVG in web design?

SVG stands for Scalable Vector Graphics, a widely used XML-based vector image format. It allows creating of graphics that can be scaled to any size without losing quality. SVG is significant in web design as it provides a flexible, lightweight solution for displaying high-quality website images and animations. Designers and developers prefer SVG files due to their easy editing and manipulation using various software tools.

Role of CSS in Animation:

Brush up on the basics of CSS animation properties, including keyframes, transitions, and transforms. These form the foundation for bringing SVGs to life on your web pages. Utilizing these techniques can create engaging and dynamic visual experiences for your audience. These techniques can create engaging and dynamic visual experiences for your audience that will leave a lasting impression.

Basic SVG Structure:

Unlike raster images, SVGs are based on XML and define graphics using mathematical equations. This vector format allows seamless scaling without losing quality, making SVGs ideal for responsive design across various devices.

SVG files begin with an <svg> element, serving as the container for graphic elements. Within this container, various aspects like <rect>, <circle>, and <path> define shapes and components of the graphic.

<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
  <circle cx="50" cy="50" r="40" fill="blue" />
</svg>

Basic SVG Animation Techniques

Applying Transitions:

Create smooth transitions in CSS and apply them to SVG elements. Transitioning properties like colour, size, and position can give your designs a professional look.

Using Keyframes for Complex Animations:

Dive into the world of keyframes to create intricate and customized animations. Understand how to control the trajectory, timing, and easing functions to craft captivating motion effects.

Advanced Techniques for SVG Animation

3D Transformations

Incorporating 3D transformations in your SVG animations can help you surpass two-dimensional graphics limits. This will add a sense of depth and realism to your designs. You can also experiment with lighting effects and perspective to enhance the visual impact. Using CSS 3D transformations, you can create visually stunning and immersive experiences on the web.

@keyframes spin {
  from { transform: rotateY(0deg); }
  to { transform: rotateY(360deg); }
}

.svg-element {
  animation: spin 4s infinite linear;
  transform-style: preserve-3d;
}
Animating Paths and Shapes

Uncover the secrets of animating the paths and shapes within your SVGs. From morphing to complex transformations, learn to create mesmerizing effects that captivate your audience.

Interactive Animations with CSS and JavaScript:

Elevate your SVG animations by integrating JavaScript for interactive elements. Explore how to trigger animations based on user interactions, creating a more engaging and user-friendly experience.

Filter Effects:

Enhance your SVG animations with filter effects. Apply filters like blur, drop shadow, and colour manipulation to create artistic and visually appealing animations.

@keyframes blurIn {
  from { filter: blur(0px); }
  to { filter: blur(10px); }
}

.svg-element {
  animation: blurIn 2s ease-in-out infinite alternate;
}
Attributes and Styling in SVG:

SVGs support a range of attributes that control their appearance and behaviour. Common attributes include:

  • Fill for setting the fill colour.
  • Stroke for defining the 'stroke' colour.
  • Stroke-width for specifying the stroke width.
<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
  <rect width="80" height="80" fill="yellow" stroke="black" stroke-width="2" />
</svg>

Example 1

Add SVG into the HTML where you want the ad. you'll do something like:

html

<div class="module module-ad">
           <svg version="1.1" id="wufoo-ad" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 400 400" enable-background="new 0 0 400 400" xml:space="preserve">

                <!-- background -->
                <rect class="wufoo-background" fill="#D03E27" width="400" height="400" />

                       <!-- logo letters -->
                       <path class="wufoo-letter" fill="#F4F4F4" d="M60.858,129...." />
                       <path class="wufoo-letter" fill="#F4F4F4" d="..." />
                                  <!-- etc -->

                       <!-- dinosaur -->
                       <g class="trex">
                                     <path ... />
                                     <path ... />
                       </g>

           </svg>
  </div>

The words fade in and out first.

To begin, we must showcase the qualities of being fast, intelligent, and formidable. Each word will be displayed for one second, with an animation that only shows the text for 10% of the total time.

css

@keyframes hideshow {
      0% { opacity: 1; }
       10% { opacity: 1; }
       15% { opacity: 0; }
       100% { opacity: 0; }
}

Then target that first word and have the animation last for 10 seconds (10% of that is 1 second):

.text-1 {
      animation: hideshow 10s ease infinite;
}

The following two letters will start hidden (opacity: 0;) and then use the same animation, only delayed to create a bit later:

.text-2 {
      opacity: 0;
       animation: hideshow 10s 1.5s ease infinite;
}
.text-3 {
       opacity: 0;
       animation: hideshow 10s 3s ease infinite;
}

The extra 0.5s on each accommodates the fading-out period of the word before it.

To make the animation fit into our 10-second timeline and be centered where we want it, we will create a 5-second animation that plays forward and backward. This way, we only need to scale it in one direction because it will automatically scale back when it reverses.

The letters are delayed slightly, causing them to appear slightly off-kilter. This is achieved through the use of the following CSS animation code on the.

css

.wufoo-letter {
      animation: kaboom 5s ease alternate infinite;
       &:nth-child(2) {
               animation-delay: 0.1s;
       }
       &:nth-child(3) {
               animation-delay: 0.2s;
       }
       &:nth-child(4) {
               animation-delay: 0.3s;
       }
       &:nth-child(5) {
               animation-delay: 0.4s;
       }
}
@keyframes kaboom {
       90% {
               transform: scale(1.0);
       }
       100% {
               transform: scale(1.1);
       }
}

The above is in SCSS just for brevity and includes no prefixing.

It could be helpful to have CSS natively randomized animation-delay property. It would be interesting to observe the letters being delayed randomly every time.

Example 2

Animating a Hamburger Menu Toggle

We will discover the seamless animation process for a menu toggle. That transforms a "hamburger" icon into a close button ("X"). To achieve this, we must first grasp the fundamentals of animating SVGs.

<button>

     <svg class="hamburger">

          <line x1="0" y1="50%" x2="100%" y2="50%" class="hamburger__bar hamburger__bar--top" />

          <line x1="0" y1="50%" x2="100%" y2="50%" class="hamburger__bar hamburger__bar--mid" />

          <line x1="0" y1="50%" x2="100%" y2="50%" class="hamburger__bar hamburger__bar--bot" />

     </svg>

</button>

This is a subtle but valuable animation. It attracts the user's attention, informing them that the icon can close the menu.

The lines in the image have two sets of attributes: x1 and y1 represent the starting coordinates, while x2 and y2 represent the ending coordinates. We used relative units to position them, ensuring the image resized to fit the SVG element. However, this method has a drawback: we can't maintain the aspect ratio of the elements. To do so, we need to use the viewBox attribute of the <svg> element.

Please note that CSS classes were used to apply styles to the SVG elements. This makes modifying different properties through CSS easy, enabling basic styling for SVG elements.

  • We will adjust the size and change the cursor type to make the <svg> element clickable. However, we will use the stroke and stroke-width properties to select the line color and thickness instead of the color or border properties. SVG sub-elements are not HTML elements and have different property names.
css

.hamburger {
      width: 62px;
       height: 62px;
       cursor: pointer;
}
.hamburger__bar {
       stroke: white;
       stroke-width: 10%;
}

  • When we render now, we'll notice that the three lines are the same size and position, with no space in between. Although we can't adjust the starting and ending positions separately through CSS, we can shift entire elements using the transform property. We'll need to move the top and bottom bars to achieve this.
css

body {
      display: flex;
       justify-content: center;
       align-items: center;
       background-color: #222;
       height: 100vh;
}

button {
       border: none;
       background: none;
       cursor: pointer;
}

.hamburger {
       width: 62px;
       height: 62px;
}

.hamburger__bar {
       transition-property: transform;
       transition-duration: 0.3s;
       transform-origin: center;
       stroke: white;
       stroke-width: 10%;
}

.hamburger__bar--top {
       transform: translateY(-40%);
}

.hamburger__bar--bot {
       transform: translateY(40%);
}

.is-opened .hamburger__bar--top {
       transform: rotate(45deg);
}

.is-opened .hamburger__bar--mid {
       transform: scaleX(0.1);
}

.is-opened .hamburger__bar--bot {
       transform: rotate(-45deg);
}

Optimization and Best Practices

Optimize SVG for Performance:

Optimize your SVG code to reduce file size and improve performance. Use SVGO (SVG Optimizer) tools to remove unnecessary elements, attributes, and whitespace from your SVG files.

Cross-Browser Compatibility:

Navigate potential challenges with cross-browser compatibility. Learn how to troubleshoot and ensure your SVG animations work seamlessly across web browsers.

Inline SVG vs. External SVG:

Consider including SVG directly in your HTML or as an external file. For small icons or simple graphics, inline SVG might be more convenient. An external SVG file can be easier to manage for larger and more complex pictures.

Consider JavaScript for Complex Interactions:

For more complex and interactive animations, JavaScript can be a powerful tool. Libraries like GreenSock Animation Platform (GSAP) provide robust tools for animating SVG elements.

Use ViewBox for Responsive Scaling:

Use the viewBox attribute in your SVG to maintain proper aspect ratios and enable responsive scaling. This ensures your SVG animations look good across various screen sizes.

This best practices help you to create smooth, performant, and accessible SVG animations in your web projects.

Conclusion:

With the right strategy and implementation, you can create visually stunning designs for your project. I hope our guide helps you choose the right way to implement CSS in your web development to improve the quality of your project. Also, by following the best practises suggested by our developers, you can improve your CSS graphic skills and create even more impressive designs for your project.

Elightwalk provides a variety of technological content to improve developers skills and help others improve their coding abilities. Contact us for any kind of guidance related to your project, or hire our developers to work on your project to get high-quality results.

Ravi Baghel
Frontend Developer

A professional frontend developer with 5 years of experience who excels in tackling complex challenges. Their expertise focuses on creating SEO- and mobile-friendly products that fit customer needs. He works closely with fellow front-end engineers, helping to adopt best practices and stay abreast of new technologies.

Most Visited Blog

Blog
Wildcard Selectors (*, ^ and $) in CSS for classes

A Wildcard selector is used to select multiple elements simultaneously. It selects a similar type of class name or attribute and uses CSS property. * wildcard also known as containing wildcard.

Read More
Blog
How to Use Margin-Inline and Margin-Block for Maximum Efficiency?

Maximize the efficiency of your CSS! Learn how to utilize Margin-Inline and Margin-Block efficiently for fine layout control. Optimize your web development spacing by simplifying your design strategy.

Read More
Blog
Simple Steps to Modify Your Cursor Colour

Elevate your web design with a pop of colour! Follow these easy instructions to change the colour of cursor easily and add a personalized touch to improve the visual appeal of your website.

Read More