How to create and use an SVG Sprite

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
- This is my all time favorite method for implementing SVGs. In my humble opinion, it's the cleanest way with the most flexibility. You can resize the SVG, change the color, and even better, only making one HTTP request that can then be cached and used across your entire site, so without further ado. (upbeat music) If you're new to SelfTeach.me channel, my name is Amy Dutton, I'm a web designer and developer. If you're just getting into this space sometimes it's hard to know where to start or what resources to trust, I want to help you level up and get to where you want to be. If this sounds interesting to you, hit the subscribe button below. This is part four of a multi-part series on SVGs. If you're interested, I've included links to all the other videos in the description below, along with the link to the playlist or it'll also be above. Okay, with this method, we are going to create an SVG sprite and you might be wondering, what's a sprite? (keyboard clicking) Huh? Sprites were really popular back when everyone was using pings for all of their images. Companies would make a single image that would have all of their icons or logos or emojis all in one place. Then you'd use this as a CSS background image and only show the part of the graphics that you wanted to display. This is helpful because your website would make one HTTP request instead of potentially hundreds. Plus this image could be cached and then used on almost every single page of your site. An SVG sprite is similar, it has all of your SVGs baked into a single file, but it's a heck of a lot easier to work with because you don't have to worry about size and placement. There are scripts out there that will automate this process and generate this sprite for you. So you just put all your SVGs in a single folder and a tool like Web Pack will look into that folder and grab any and all the SVGs in there and build this sprite for you. Just give it a Google, but for today we're not gonna get that fancy. There are a few online tools that we're going to use and most of the tools do come with a command line interface. So even if you want to run this process locally on your computer, in your terminal, you can. Okay, as always, I've included links to these tools within the description below. The first tool that we're going to look at is the SVG sprite generator. If you pull this up in a browser, you'll see that it says drop SVG files to create the sprite. So I have a handful of social media icons and I'm just going to drag and drop, awesome. This section at the bottom is our SVG sprite and we can copy the content, download it or open it directly within CodePen. I'm going to open it within CodePen. If you've never used CodePen before, it's a code sandbox that is great for experimenting with code or sharing code snippets and you can set up a free account. Okay, so let's walk through this. On the CSS side, we don't have much it's just an icon definition with the height, the width and margin. On HTML side, at the top we have our SVG and you'll notice that it has a height of zero and a width of zero, interesting, interesting. Then we have these symbols and this looks similar to what we're used to seeing. There's a view box, which corresponds with this particular icon's height and width and each symbol has an ID related to the icon that we uploaded. So there's one for CodePen and Dribble and Facebook and so on, interesting. Then we have these paths with all these crazy numbers. In our display at the bottom you'll notice that the CodePen logo is black while all the other logos are pink. And if we can look at the CodePen symbol, there's not a fill attribute defined, but there are fill attributes on all the other symbols assigned to this pink color, interesting. If we scroll down to the bottom, there's a comment that says SVG references, interesting. So what's going on here? Well, at the top we have our SVG sprite and this has all the references to all the individual SVGs. Yes, it has a width of zero and a height of zero because this isn't actually visible on the page. The content is just here so that we can reference it. Then here at the bottom, these are our SVG definitions that reference our icon CSS class. It's limiting the size and the margins so that the icons are sized and spaced consistently. And inside the SVG tag, there's a use tag that references the sprite above and tells the browser which piece to pull in. It is worth noting that the excellent HREF attribute has just been updated to href. So we could update these if you like but I'm willing to bet excellent href will continue to be supported. And if you're interested, I'll include a link in the description below with some more information on that. Okay, this method will also allow us to control the color from our CSS. So let's add a field property to our icon definition. That's strange only our first icon that was originally black change colors. Why do you think that is? Well, if you scroll up and look at the symbol definition you'll notice that it doesn't have the attribute defined but all of the other icons have a fill attribute that override our CSS, it works like an inline style. As soon as we remove those fill attributes everything will work just like we would have hoped. Now we could do this for every icon but it does start to get a little tedious. So let's use a command line tool that will do the job for us. The command line tool requires a little bit of upfront setup, but it's something that you do once and then it will speed up your workflow in the long run. So the tool that we're going to use is called SVGO I'm not exactly sure if that's SVG GO or SVGO anyways, the O stands for optimizer. If we load up the documentation within the browser and scroll down you'll see there's a line to install it. Lets you run this within the terminal. And it doesn't really matter what folder you are when you run it. Because of that dash G that's a flag that installs this globally making them accessible anywhere. And my terminal might look a little bit different than yours since I already have this installed. Let's flip over and look at some of the documentation. This section at the top includes all the plugins that you can use in their default values. There's a lot, let's scroll back down and you'll see a section that explains all the options that you can pass in. And then at the bottom there are several examples and you'll see there are options for passing in files or folders. And you can also specify how you want the files to be output whether they'll be overriding the existing files or they'll be saved elsewhere with different names. But we need to set up a configuration file so that we can remove the fill and stroke attributes for us. I put my config file and it just on GitHub I'll include a link in the description below. Feel free to download it, change it, use it, whatever. Okay, so I'll walk you through the process. I'm going to click on the download zip button. Then I'm going to put my config file into my user folder. And this is where all my user preferences are stored. I know that's hard to believe since you don't see any files within this folder but all those preference files start with the period. So they're hidden within the finder. If I opened the terminal and type L S- A it will list everything and you'll see a whole stream of files that start with a period. I want this SVG config file to be consistent with the other preference files. Plus I'd like to hide it. So I'm going to rename it to have a period at the front. Okay, now let's go to the folder where we have our icons. I'm going to make this easy on myself and type cd and then drag and drop the folder onto the terminal window. Okay, I'm gonna hit enter and let's run our command. So I'm going to say SVGO and I'm going to grab all the SVGs in this folder. So I'm gonna use asterix and I'm not going to include an output path that can just overwrite what's currently there. I'm going to point to our config file. Make sure you use the double dashes otherwise this won't work. So I'm going to say config equals. Then I may pass it a path to our files. I'm going to say users Amy Dutton dash SVGO config dot Jason, hit enter and it should run our script. When it's finished, it'll tell you how much it cut down on each file, then if we open one of these, say the Facebook SVG you won't find any fill attributes. If you have OMI ZSH running, we can actually set up an alias to run this command and actually have a separate video on OMI. ZSH link in the description and the part above. By setting up an alias, we don't have to run this command every single time. Remember we're trying to work smarter, not harder. So I'm going to pull up my config file. And this is actually an alias that I've written to pull up my config file. So at the bottom of this file, I have all my aliases listed out. So let's create another one for SVGO I'll say alias. And we'll call this SVG me and we'll say equals and I'll just type out our command. It's going to grab all SVGs config. Users, Dutton SVGO- config dot Jason and give that a save. We'll probably have to restart our terminal. Now, if I type in CD, grab our SVG file and just type SVGME and it will run our command. These say 0% because we have already compressed everything. Now that all of our SVG files are cleaned up. Let's generate that Sprite again, except this time instead of dragging and dropping them into a web tool let's use another command line tool, SVG Sprite generator. Again, I'll include a link in the description below. So if we look at the documentation to install it says we need to run this line. So I'm going to give that a copy and paste that into our terminal. You'll notice that -G again means that it's installing it globally. And once this is done installing, we can run this line. We need to get a destination and an output. Within our terminal I'm going to go up a level by typing cd.dot dot and this will make it easy to pass our entire SVG folder. So now I'm going to say SVG Sprite generate. And we want to define our directory, say SVGs and then I want to give it an output. So I'm going to say Sprite dot SVG. Now we can open up our new Sprite.SVG file within VS code. It's a lot cleaner than before. So let's copy this entire block and go back over to CodePen and we just want to remove this sprite at the top. We don't want to grab the bottom part with the user links we just want to grab this SVG. So I'm going to delete that and paste in our new Sprite. And you should see our icons jumped down and turn to that blue color. Hey, let's go to our Chrome developer tools. We could right click on one of these items and choose inspect. Or we could click on this arrow and select a specific item on our page. So if we move our mouse around, it looks like there's a block on the left of our icons. And if we click on that, it will highlight the item within our HTML. If we expand this, it's a little bit easier to see that this is our Sprite. Now remember the original Sprite had a width and a height of zero and our cleanup Sprite doesn't have that so let's add that back in. And you should see that space disappear. Okay, this is great we can even jump down to our user link definitions here at the bottom and target our Facebook icon by adding a class of Facebook And if we come over our CSS we want to say, give this a fill of purple, a width of 100 pixels and a height of 100 pixels. Okay, awesome, there's just one thing though that SVG code at the top is ugly. Good news though we can actually put that SVG Sprite into an external file. And this is really great because it makes our code more readable and we don't have this nasty block of code that's technically not even visible on our page. And the external file can be cached. Meaning your browser goes to one page of your site, caches it and then it doesn't have to download that file again for any subsequent page visits. So there is one catch though for security purposes the file has to be on the same server. So this example won't work in CodePen, but if I spin up a local server on my computer, it works like a champ. So we just switch over to vs code and you can see that have an index.HTML file and my SVG is inside a Sprite dot SVG. This is the generated code that we got from our command line interface. Within the use tag I have an excellent HREF and I have the file name and I have the pound sign and the ID for the symbol that I'm referencing, so in this case CodePen. If I switch over to my browser you can see it's loading the CodePen icon. If you're having trouble getting this to work there is one more solution hang in there with me, I know this video is getting long, but I'll try to make it worth your time. You can inject the SVG code into your page using a little bit of JavaScript and Ajax. So let's flip back over to CodePen, and I'm going to click on the assets button in the bottom left and upload our Sprite dot SVG. Let's go back over to CodePen, and I'm going to click on the assets button at the bottom, and I'm going to upload our Sprite dot SVG. Okay, then I'm going to click on the copy as button and get the URL. And within our HTML, we can delete all of this nastiness And we collapsed Our JavaScript panel before, but now we can open this back up. I'm going to create a new variable called Ajax and make a new XML HTTP request. And now we can use the open method. So we're going to use a get request to grab the contents of our SVG. So let's paste in that URL for our sprite. And then we want this to be an a sync request. I'm gonna say true. Okay, and then we want it to send our data. Once it's loaded so to say Ajax, unload, we want to run a function. If you're wondering where these functions open, send and unload are coming from, they're part of JavaScript. When you're working with this XML HTTP request object you get all of those for free. So I'll include a link to the documentation in the description below. Okay, so once it's loaded, we want to create a new div so we can create a new variable and use, create elements so I say document.create element, to make a div. Then we want to set the inner HTML to the response texts that we get back from our Ajax requests. So let's see Ajax dot response text. Then we need to insert our div at the very beginning of our HTML. Sweet, all of our icons are working again, but you'll notice that they jumped down. It's the same reason as the force so we need to give it a width, and a height of zero. And this time let's do it through CSS. So let's go back to our JavaScript and stick a class on our div that we can reference. Say div.class name equals SVG Sprite. Now we can go to our CSS panel and say, SPG Sprite with zero height is zero four. We can make it even easier and say display none. Awesome, I know it took us a while to get to that last method, but there are several things I really love about it that make it the best. You don't have that nasty SVG code at the top of the page with the Ajax request, it works best across all browsers and you don't have to worry about security issues. Plus, one thing you can do with Ajax, because it's literally injecting the entire SVG onto the page and not just referencing it, you can actually change the fill color for each individual path and not just the symbol. For the CodePen icon it would be better if I had a class name on the path itself, but I could also reference the first path like this so you could say CodePen, path, first trial fill is pink. We give that a save, there we go. Now you have a two-tone icon, phew. That was fun, maybe. If you're working on a React project I would recommend checking out my ultimate icon component video, link in the card above. React has a unique way of doing things and that video explains how I apply these concepts to React, ton. (upbeat music) so far in the series we've covered seven different ways that you can get an SVG on a page. So if you're having trouble keeping all these methods straight or if you'd like something for quick reference, you're in luck, I've created a free cheat sheet that outlines each method along with the pros and cons for each, so link in the description below. All the code for this video is posted on CodePen and GitHub, links in the description below feel free to download it, copy it, modify it, use it whatever it's yours. In the next couple of videos we're going to get into the fun stuff and talk about no. Manipulating SVGs, creating custom graphs, animating, so be sure to click the subscribe button below and the bell icon there, so you can get notifications, so you don't miss out on Once these videos are posted until then keep going. (upbeat music) (indistinct speaking)
Info
Channel: Self Teach Me
Views: 4,602
Rating: undefined out of 5
Keywords: svg sprite, svg sprite in css, svg sprite not working, svg sprite how to use, svg sprite setup, svg sprite tutorial, svg tutorial, svg tutorial html5, svg tutorial html, svg for beginners, svg beginner tutorial, scalable vector graphics, svg, svg spritesheet, svg sprite as external file, svg icons, svg icon system, svg style, svg use, svg css
Id: LgfLpEHqgGU
Channel Id: undefined
Length: 18min 28sec (1108 seconds)
Published: Tue Mar 09 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.