- How to Use SVG Images in CSS and HTML – A Tutorial for Beginners
- Why should you use SVG images?
- How to download the SVG image used in this tutorial
- How to use SVG images in CSS and HTML
- 2. How to use SVG as a CSS background-image
- 4. How to use an SVG as an You can also use an HTML element to add SVG images to a webpage using the code syntax below:
You use the data attribute to specify the URL of the resource that you'll use by the object, which is the SVG image in our case.
You use the width and height to specify the size of the SVG image.
Again, below is a demo for you to explore. 😃
Using the is supported across all browsers that support SVG.
5. How to use SVG as an
Even though this isn't advisable, you can also add an SVG image using an as seen in the demo below.
Just keep in mind, though, that s can be difficult to maintain and will be bad for your site's Search Engine Optimization (SEO).
Using also defeats the purpose of the Scalable in the name Scalable Vector Graphics because SVG images added with this format are not scalable.
6. How to use SVG as an
The HTML element is another way to use an SVG image in HTML and CSS using this syntax: .
Keep in mind, however, that this method has limitations, too. According to MDN, most modern browsers have deprecated and removed support for browser plug-ins. This means that relying upon is generally not wise if you want your site to be operable on the average user's browser.
Below is a demo of using the HTML element to add an SVG image.
Conclusion
I hope you were able to learn about the different ways of using SVG images in CSS and HTML. This will hopefully guide you towards choosing the right method when adding SVG images to a website.
If you have any questions, you can send me a message on Twitter, and I'll be happy to answer every single one.
How to add SVGs with CSS (background-image)
There are TWO methods for displaying SVG images as a CSS background image:
Notice with this method we have to treat the SVG code before it will work. In the example, we convert the SVG to a Data URI. You could even convert it to Base64, but that will result in a messier, longer code blob. It is a best practice to avoid Base64 in this case.
Tip: Use this SVG to CSS converter tool to quickly convert your SVG code into a data URI.
After you place your file path or SVG code into the background-image property, you can further tweak how the background displays. You see, the great thing about using an SVG as a CSS background-image is that they can be styled with CSS background properties.
The CSS background-image properties
Let’s review all the properties related to background-image and what they do.
- Background-attachment:
Example values: scroll; fixed; local;
The attachment specifies how the background moves relative to the user’s screen. When the user scrolls, the background can scroll along with a given section, or stay put ( fixed ).
- Background-position:
Example values: center; top left; 50% 50%; right 30px bottom 15px;
The background-position determines where the image is displayed within its container. The center keyword is great with large backgrounds and at making patterns symmetrical. With smaller backgrounds, you may reach for a combo of keywords and lengths to place the background image more precisely. - Background-size:
Example values: cover; contain; 500px 250px; auto;
This controls how big or small the image displays. A value of cover forces the image to fill its entire containing element in proportion, and either the excess width or height will get clipped. A value of contain is similar in that it fills its container in proportion, but without clipping. You can also provide a specific width and height value. - Background-repeat:
Example values: no-repeat; repeat; repeat-x;
The background-repeat property allows you to tile the background image into a pattern. - Background-color:
Example values: red; #F00; rgb(0,255,165);
SVGs are a transparent image format and if the SVG elements do not cover the entire viewBox, the background color will be visible behind your SVG. - Background-origin:
Example values: border-box; padding-box; content-box;
The origin determines the boundary of the background’s container. Border-box will stretch the background area for the entire container, while the padding-box and content-box values shrink the background area within the border and inside the padding respectively.
- Background-clip:
Example values: border-box; padding-box; content-box;
Similar to background-origin , this property defines the background area, with one difference: the background doesn’t resize, but instead crops the background image to fit in the assigned boundary.
- Background-blend-mode:
Example values: multiply; screen; overlay, color-dodge, color;
This property blends the colors of the target background with what is visible behind the target element, blending into a single colorful result. The blend modes are essentially the browser version of Photoshop’s blending modes.
Layering multiple background images
Background-image can hold multiple background image layers to achieve cool effects. To create these image layers, comma-separate each image value in a single background-image property. Then when you use any related background properties, comma-separate those varied values to coincide with the images, or instead use a single value which will apply to all images the same.
You can mix images, SVG data URIs, and CSS gradients. But you need to overlap images with transparency or take advantage of the background-blend-mode discussed above. Otherwise you will only see one background. The first image is on top of the background stack. Let’s mix a few backgrounds now, and see what we get. First I headed over to the homepage of SVGBackgrounds.com to find a few quick backgrounds to layer together. Here is the code and results: BUT, this technique prevents the need to layer div containers to achieve a layer effect. Let’s try again, this time to make a simpler one that looks useable. Let’s place a pattern over a cool image texture. Much better! I could definitely see something more like this being used in a real-world project. Subtle backgrounds are always nice. Wrapping up about SVGs in CSS background-images We looked at how to add SVGs into the CSS property background-image . With all the related background properties and the fact you can layer backgrounds, there is little that can’t be achieved. This way of adding website backgrounds is powerful. ), the creator behind SVG Backgrounds. Hire me to help you with design on your website or app. ), the creator behind SVG Backgrounds. I produce free and paid resources every few months, sign up for alerts. Источник Подключаем SVG-иконку на сайт и меняем цвет через CSS HTML, CSS В предыдущих сериях… В прошлой статье мы выяснили, в чем отличие растровых форматов изображения от векторных. Теперь будем работать с векторной графикой. Для начала, научимся подключать эти изображения разными способами. Возьмем стандартную папку с проектом, в которой есть отдельная папка для изображений, отдельная — для файлов .css , а также файл .html Подключение через тег в html Работаем как с обычной картинкой. Тег , атрибут src , прописываем путь к файлу. Можно использовать любые атрибуты , включая атрибут width . Иконки Подключение фона в .css Можно подключить svg-графику в качестве фона элемента. Часто используются фоновые паттерны. Это небольшой фрагмент, впоследствии повторяющийся и создающий орнамент. Укажите в html нужный класс и пропишите свойства фона background-image в файле css. Используйте функцию url() , чтобы задать путь к файлу с изображением. /* SVG фоновое изображение */ .block-bg < width: 600px; height: 200px; background-image: url('./../img/bg-zigzag.svg'); > Описываем svg-графику inline Существуют специальные теги и атрибуты для описания графики прямо в коде. При этом, изображение становится интерактивным — мы можем, например, менять цвет, или размер по наведению на иконку. Тег используется как контейнер для хранения SVG графики. При помощи тега и его атрибутов создается фигура. Посмотрите, как выглядит иконка YouTube в inline формате. Стилизуем в файле .css по классу youtube-icon . Будем менять цвет иконки по наведению при помощи свойства fill . /* SVG inline код. Смена цвета по ховеру */ .youtube-icon < width: 64px; height: 64px; fill: black; >.youtube-icon:hover Заключение Мы разобрали 3 стандартных способа подключения SVG-графики на сайт: тег , свойства CSS, тег . Узнали про то, как можно менять цвет SVG-иконки через CSS и свойство fill . В следующей статье продолжим работу с тегам , , разберем как можно ещё кастомизировать векторную графику. Источникbackground-image: url( '/path/image-1.svg' ), url( '/path/image-2.svg' ), url( '/path/image-3.svg' );
- Background-attachment:
- Much better!
- Wrapping up about SVGs in CSS background-images
- Подключаем SVG-иконку на сайт и меняем цвет через CSS
- В предыдущих сериях…
- Подключение через тег в html
- Иконки
- Подключение фона в .css
- Описываем svg-графику inline
- Заключение
How to Use SVG Images in CSS and HTML – A Tutorial for Beginners
SVG stands for Scalable Vector Graphics. It is a unique type of image format for vector-based graphics written in Extensible Markup Language (XML).
In this tutorial, I will explain why you’d want to use SVG images and how you can use them in CSS and HTML.
Why should you use SVG images?
There are a number of reasons to use SVG images, some of which are:
- SVG images do not lose their quality when zoomed or resized.
- They can be created and edited with an IDE or text editor.
- They are accessible and animatable.
- They have a small file size and are highly scalable.
- And they can be searched, indexed, scripted, and compressed.
Now let’s see how you can actually work with SVG images.
How to download the SVG image used in this tutorial
If you want to work with the SVG image I’ve used in this tutorial, follow the steps (and diagram) below to download it.
- Go to unDraw.
- Change the background color to yellow.
- In the search box, search for the word happy.
- Click on the image named Happy news.
- On the pop-up window, click on the Download SVG to your projects button.
If you followed the steps above correctly, the SVG image should be on your computer now.
Now, open the SVG image in your favorite IDE or text editor. Rename it to happy.svg or whatever name you prefer.
How to use SVG images in CSS and HTML
There are several different ways to use SVG images in CSS and HTML. We will explore six different methods in this tutorial.
1. How to use an SVG as an
This method is the simplest way to add SVG images to a webpage. To use this method, add the element to your HTML document and reference it in the src attribute, like this:
Assuming you downloaded the SVG image from unDraw and renamed it to happy.svg, you can go ahead and add the code snippet above into your HTML document.
If you did everything correctly, your webpage should look exactly like the demo below. 👀
When you add an SVG image using the tag without specifying the size, it assumes the size of the original SVG file.
For instance, in the demo above, I didn’t modify the size of the SVG image, so it assumed its original size (which was a width of 915.11162px and a height of 600.53015px ).
Note: to change the original size, you have to specify the width and height with CSS as you can see in the demo below. You can also update the original width and height directly.
Even though we can change the size of SVG images added via the tag, there are still some restrictions if you want to make major style changes to the SVG image.
2. How to use SVG as a CSS background-image
This is similar to adding SVG to an HTML document using the tag. But this time we do it with CSS instead of HTML as you can see in the code snippet below.
SVG images can be written directly into the HTML document using the tag. To do this, open the SVG image in VS code or your preferred IDE, copy the code, and paste it inside the When you use SVG inline in the HTML document, it reduces load time because it serves as an HTTP request. Using this method lets you perform more customization as opposed to using either the You can also use an HTML You use the data attribute to specify the URL of the resource that you'll use by the object, which is the SVG image in our case. You use the width and height to specify the size of the SVG image. Again, below is a demo for you to explore. 😃 Using the is supported across all browsers that support SVG. 5. How to use SVG as an Even though this isn't advisable, you can also add an SVG image using an as seen in the demo below. Just keep in mind, though, that s can be difficult to maintain and will be bad for your site's Search Engine Optimization (SEO). Using also defeats the purpose of the Scalable in the name Scalable Vector Graphics because SVG images added with this format are not scalable. 6. How to use SVG as an The HTML element is another way to use an SVG image in HTML and CSS using this syntax: . Keep in mind, however, that this method has limitations, too. According to MDN, most modern browsers have deprecated and removed support for browser plug-ins. This means that relying upon is generally not wise if you want your site to be operable on the average user's browser. Below is a demo of using the HTML element to add an SVG image. I hope you were able to learn about the different ways of using SVG images in CSS and HTML. This will hopefully guide you towards choosing the right method when adding SVG images to a website. If you have any questions, you can send me a message on Twitter, and I'll be happy to answer every single one. There are TWO methods for displaying SVG images as a CSS background image: Notice with this method we have to treat the SVG code before it will work. In the example, we convert the SVG to a Data URI. You could even convert it to Base64, but that will result in a messier, longer code blob. It is a best practice to avoid Base64 in this case. Tip: Use this SVG to CSS converter tool to quickly convert your SVG code into a data URI. After you place your file path or SVG code into the background-image property, you can further tweak how the background displays. You see, the great thing about using an SVG as a CSS background-image is that they can be styled with CSS background properties. Let’s review all the properties related to background-image and what they do. Background-image can hold multiple background image layers to achieve cool effects. To create these image layers, comma-separate each image value in a single background-image property. Then when you use any related background properties, comma-separate those varied values to coincide with the images, or instead use a single value which will apply to all images the same. You can mix images, SVG data URIs, and CSS gradients. But you need to overlap images with transparency or take advantage of the background-blend-mode discussed above. Otherwise you will only see one background. The first image is on top of the background stack. Let’s mix a few backgrounds now, and see what we get. First I headed over to the homepage of SVGBackgrounds.com to find a few quick backgrounds to layer together. Here is the code and results: BUT, this technique prevents the need to layer div containers to achieve a layer effect. Let’s try again, this time to make a simpler one that looks useable. Let’s place a pattern over a cool image texture. I could definitely see something more like this being used in a real-world project. Subtle backgrounds are always nice. We looked at how to add SVGs into the CSS property background-image . With all the related background properties and the fact you can layer backgrounds, there is little that can’t be achieved. This way of adding website backgrounds is powerful. ), the creator behind SVG Backgrounds. Hire me to help you with design on your website or app. ), the creator behind SVG Backgrounds. I produce free and paid resources every few months, sign up for alerts. HTML, CSS В прошлой статье мы выяснили, в чем отличие растровых форматов изображения от векторных. Теперь будем работать с векторной графикой. Для начала, научимся подключать эти изображения разными способами. Возьмем стандартную папку с проектом, в которой есть отдельная папка для изображений, отдельная — для файлов .css , а также файл .html Работаем как с обычной картинкой. Тег , атрибут src , прописываем путь к файлу. Можно использовать любые атрибуты , включая атрибут width . Можно подключить svg-графику в качестве фона элемента. Часто используются фоновые паттерны. Это небольшой фрагмент, впоследствии повторяющийся и создающий орнамент. Укажите в html нужный класс и пропишите свойства фона background-image в файле css. Используйте функцию url() , чтобы задать путь к файлу с изображением. Существуют специальные теги и атрибуты для описания графики прямо в коде. При этом, изображение становится интерактивным — мы можем, например, менять цвет, или размер по наведению на иконку. Тег используется как контейнер для хранения SVG графики. При помощи тега и его атрибутов создается фигура. Посмотрите, как выглядит иконка YouTube в inline формате. Стилизуем в файле .css по классу youtube-icon . Будем менять цвет иконки по наведению при помощи свойства fill . /* SVG inline код. Смена цвета по ховеру */ .youtube-icon < width: 64px; height: 64px; fill: black; >.youtube-icon:hover
3. How to use inline SVG images
element in your HTML document.
or
background-image
methods.4. How to use an SVG as an
element to add SVG images to a webpage using the code syntax below:
Conclusion
How to add SVGs with CSS (background-image)
The CSS background-image properties
Example values: scroll; fixed; local;
The attachment specifies how the background moves relative to the user’s screen. When the user scrolls, the background can scroll along with a given section, or stay put ( fixed ).
Example values: center; top left; 50% 50%; right 30px bottom 15px;
The background-position determines where the image is displayed within its container. The center keyword is great with large backgrounds and at making patterns symmetrical. With smaller backgrounds, you may reach for a combo of keywords and lengths to place the background image more precisely.
Example values: cover; contain; 500px 250px; auto;
This controls how big or small the image displays. A value of cover forces the image to fill its entire containing element in proportion, and either the excess width or height will get clipped. A value of contain is similar in that it fills its container in proportion, but without clipping. You can also provide a specific width and height value.
Example values: no-repeat; repeat; repeat-x;
The background-repeat property allows you to tile the background image into a pattern.
Example values: red; #F00; rgb(0,255,165);
SVGs are a transparent image format and if the SVG elements do not cover the entire viewBox, the background color will be visible behind your SVG.
Example values: border-box; padding-box; content-box;
The origin determines the boundary of the background’s container. Border-box will stretch the background area for the entire container, while the padding-box and content-box values shrink the background area within the border and inside the padding respectively.
Example values: border-box; padding-box; content-box;
Similar to background-origin , this property defines the background area, with one difference: the background doesn’t resize, but instead crops the background image to fit in the assigned boundary.
Example values: multiply; screen; overlay, color-dodge, color;
This property blends the colors of the target background with what is visible behind the target element, blending into a single colorful result. The blend modes are essentially the browser version of Photoshop’s blending modes.Layering multiple background images
background-image: url( '/path/image-1.svg' ), url( '/path/image-2.svg' ), url( '/path/image-3.svg' );
Much better!
Wrapping up about SVGs in CSS background-images
Подключаем SVG-иконку на сайт и меняем цвет через CSS
В предыдущих сериях…
Подключение через тег в html
Иконки
Подключение фона в .css
/* SVG фоновое изображение */ .block-bg < width: 600px; height: 200px; background-image: url('./../img/bg-zigzag.svg'); >
Описываем svg-графику inline
Заключение