In this tutorial, we'll delve into how to import and utilize SVG files in your Vite projects. SVGs (Scalable Vector Graphics) offer a means to create scalable, high-quality graphics that can be manipulated with CSS and JavaScript.
By the end of this tutorial, you will learn:
- How to import SVGs into your Vite project
- Manipulating SVGs using CSS and JavaScript
Prerequisites:
- Basic knowledge of HTML, CSS, and JavaScript
- Familiarity with Vite
In your Vite project, you can import SVGs just like any other JavaScript module:
import myLogo from './my-logo.svg';
By doing this, you are actually importing the URL of the SVG file. This URL can be used in your HTML in img
tags:
<img src={myLogo} alt="My Logo">
SVGs are made up of XML-based vector images and are treated as Document Object Model (DOM) elements in the browser. This means they can be styled and manipulated using CSS:
<style>
svg {
width: 100px;
height: 100px;
fill: red;
}
</style>
Similarly, you can manipulate SVGs using JavaScript by accessing the SVGs' DOM API:
const svgElement = document.querySelector('svg');
svgElement.style.fill = 'red';
// Import the SVG file
import myLogo from './my-logo.svg';
// Now `myLogo` is the URL of the SVG file, you can use it in your HTML
console.log(myLogo); // Expected output: "/assets/my-logo.49a45d.svg"
<style>
/* Change the color and the size of the SVG */
svg {
width: 100px;
height: 100px;
fill: red;
}
</style>
// Select the SVG element
const svgElement = document.querySelector('svg');
// Change the color of the SVG
svgElement.style.fill = 'red';
In this tutorial, we've learned how to import SVGs into a Vite project and how to manipulate them using CSS and JavaScript.
Next, you could explore more about SVGs and how to animate them using CSS or JavaScript.
Here are some resources for further learning:
- SVG Tutorial - W3Schools
- SVG Basics—How to Create Simple Shapes and Lines - Tuts+
Solutions:
fill
property in CSS to change the color, and width
and height
properties to change the size.fill
property of the SVG using JavaScript when the button is clicked. Remember, practice makes perfect! Keep experimenting with different SVGs and manipulating them using CSS and JavaScript.