Add SVG as a background image to a CSS class
If you want to set a background image for an element in CSS, you can do it at least in 2 ways. Which one fits you, it depends on your tasks and the tools you work with. This way of adding a SVG image as a background can be applied for any CSS property, for which you can add image.
The first way to set background for SVG file is to write the path to SVG file.
.skills {
background-image: url('../img/skills.svg');
cursor: pointer;
}
It’s very easy – you should upload the file to the server and to fill the path.
This way is good for:
- for the development process - you can easily watch the file and update it
- for cases, when the size of file is large;
- for cases when the image is used on small quantity of pages.
Another way, which is a bit less flexible, is to add SVG image code to the CSS property as text. As you know, SVG (Scalable Vector Graphics) is an XML-based vector image format. Unlike other image popular formats, such as JPEG, PNG or GIF, SVG is a text. And with a quick action you can transform the SVG image for inserting into CSS file. To embed the SVG image to a CSS property, you need to transform the image code with URL encode operation.
.answers {
background: url("data:image/svg+xml, %3Csvg%20height%3D%2264%22%20width%3D%2264%22%20style%3D%22overflow%3Avisible%3Benable-background%3Anew%200%200%2032%2032%22%20viewBox%3D%220%200%2032%2032%22%20%20xml%3Aspace%3D%22preserve%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%3E%3Cg%3E%3Cg%20id%3D%22Error_1_%22%3E%3Cg%20id%3D%22Error%22%3E%3Ccircle%20cx%3D%2216%22%20cy%3D%2216%22%20id%3D%22BG%22%20r%3D%2216%22%20style%3D%22fill%3A%23D72828%3B%22%2F%3E%3Cpath%20d%3D%22M14.5,25h3v-3h-3V25z%20M14.5,6v13h3V6H14.5z%22%20id%3D%22Exclamatory_x5F_Sign%22%20style%3D%22fill%3A%23E6E6E6%3B%22%2F%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E");
height: 60px;
}
Below you can prepare the SVG code for embedding to a CSS property.
One more way to convert the text of SVG image for CSS embedding is with Notepad++.
Download SVG file and open it in Notepad++, then select the text and in top menu choose Plugins / Mime Tools / URL Encode. Of course, if these plugins are installed together with Notepad++. By default they must be installed.