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.
background-image: url( '/path/image-1.svg' ), url( '/path/image-2.svg' ), url( '/path/image-3.svg' );
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 background — как правильно сделать адаптивным?
Но когда начал делать адаптив фон ведет себя не адаптивно.
При большом разрешении:
Может я не так прописываю сам фон?
Поделитесь, пожалуйста, правильным решением.
Средний 6 комментариев
Рустам Байназаров, я начал с бэкграунда. Для остального контента ещё ничего не прописывал в медиа-запросах.
Насколько я понял из самостоятельных поисков решения для адаптивности фона, что оно может быть в способе подключения СВГ как фона. Я подключил так, как в коде выше. Не знаю, как правильнее.
Spartak (Web-StyleStudio), IE не поддерживает. И это свойство прописывается к img, а у меня SVG вставлено бэкграундом.
Фоновые изображения адаптируются с помощью background-size
Или изменения размеров блока. Например, вставляются как фон псевдоэлемента и дальше регулируют размер псевдо, а фону задают contain, cover или 100% (или не 100)
Единственно отличие между растром и SVG в том, что растр меняет свои пропорции, а SVG обычно нет.
Чтобы менялись пропорции SVG у него должен быть атрибут preserveAspectRatio
Вот примеры
https://jsfiddle.net/0xrh6uvj/ — меняйте ширину окна с результатом
—-
Но вы не сделали песочницу на jsfiddle.net с вашим проблемным кодом и не ясно, что вообще вы там творите.
В процесе экспериментов я решил поставить фон для , который находится в container и как результат — при изменении ширины экрана фон не режется и вроде всё норм. Прописал ему:
background-size: cover; background-repeat: no-repeat; background-image: url(/img/back_2_section.svg);
Но. Теперь фон, естественно, будет в границах контейнера, а надо на ширину экрана.
Прописываю то же самое для самой секции (в песочнице) и фон не адаптируется, а режется.
Не понятно, почему.
Kostiantyn Kondratiuk, Потому что не адаптировано содержимое секции. Это не фон не обрезается, а содержимое вываливается из секции. Потому что у него фикс ширина 1440.
Обведите секцию рамочкой — убедитесь сами.
Ankhena, Ааа, т.е. виной всему неадаптированный контент? Значить если фон в формате СВГ то его надо адаптировать в посл. очередь дабы неадаптированный контент не сбивал с толку?