Coloring svg in css background images

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.
Читайте также:  Html input отключить автозаполнение chrome

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.

Источник

Set Fill Color of SVG Background-image

A quick guide explaining how to change the color of an SVG when it’s used as a CSS background-image.

If you want you can jump to the code, else we can explore how this works together.

SVG Background Color Fill Demo

We’ll start with a live demo, focus, hover, or click on the circle below and the background color will animate.

I’ll let the cat out of the bag.

This is just a normal button with an SVG used as a CSS mask

Instead of changing the fill color of the SVG we change the background-color of the button. But that shouldn’t spoil the fun as it opens up a world of possibilities but we’ll get to that.

Using An SVG As A CSS Mask

We can see our cool smiley SVG below 😎

svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> g stroke-linecap="round" stroke-width="4" stroke="rgb(0, 0, 0)" fill="none" > circle cx="12" cy="12" r="10" /> path d="M7 11 H17" /> g> svg>

What’s amazing about the timeline we live in is that we can pass the SVG to the CSS url() function without base64 encoding it or escaping all kinds of characters.

  1. Prefix the SVG with data:image/svg+xml,
  2. Add some structure by ending a line with \
  3. Just like that a readable SVG has appeared in our CSS.

Allright, let’s first assign the SVG to the background property so we can see it, we’ll turn it into a mask in a couple minutes.

button  /* . Other styles */ /* Color */ background-color: Crimson; /* Store the SVG in a variable so it's easy to re-use */ --svg: url('data:image/svg+xml,\ \ \ \ \ \ '); /* Assign the SVG variable */ background-image: var(--svg); > button:hover, button:focus  background-color: Turquoise; > button:active  background-color: Gold; >

We can interact with the live demo below to see the SVG has loaded and the styles are correctly applied.

Now it’s time to remove the background property and assign the —svg variable to the mask property.

The black parts of the SVG will be the visible parts of the element and the transparent parts will become invisible.

button  /* . Other styles */ /* Chrome, still requires prefix in 2022 */ -webkit-mask: var(--svg); /* Firefox and Safari */ mask: var(--svg); >

If you have trouble getting the mask to work, a handy trick is to temporarily assign the mask to the background-image property.

This allows us to visually see where the black and transparent parts of your mask are, this becomes especially useful when building more complex masks.

Any Background Goes

Because we’re masking the button we can use any background style or effect we can think of.

The Complete SVG Background-image Style Code Snippet

You can find the copy button on the right hand side of the code snippet, enjoy!

button type="button">I'm a cool circle buttonbutton> style> button  /* Base styles */ display: block; width: 4rem; height: 4rem; border: none; cursor: pointer; /* Hide button caption text */ overflow: hidden; color: transparent; /* The fill animation */ background-color: Crimson; transition: background-color 0.2s; /* Store the SVG in a variable so it's easy to use */ --svg: url('data:image/svg+xml,\ \ \ \ \ \ '); /* Chrome, still requires prefix in 2022 */ -webkit-mask: var(--svg); /* Firefox and Safari */ mask: var(--svg); > button:hover, button:focus  background-color: Turquoise; > button:active  background-color: Gold; > style>

Conclusion

We learned a nice trick where we used the CSS mask property to change the fill color of a SVG when it’s used as a background-image

On top of that we learned that the mask property is identical to the background property so we can switch them out to make debugging the mask image easier.

I share web dev tips on Twitter, if you found this interesting and want to learn more, follow me there

At PQINA I design and build highly polished web components.

Make sure to check out FilePond a free file upload component, and Pintura an image editor that works on every device.

Источник

Как менять заливку и/или контур svg в CSS при условии, что *.svg в фоне?

Его я хочу использовать в разных местах. С одним фоном и толщиной контура для одних элементов (например кнопок), без фона и другой толщиной/цветом контура (например для ссылок) и т.д. и т.п.

Каким образом для каждого элемента в CSS прописать для каждого нужного элемента свой стиль?
У всех форма одинаковая, не хотелось бы только изза заливки и толщины контура плодить несколько svg файлов.

В кратце, у нас есть один большой SVG со всеми изображениями в виде символов:

  s and whatever other shapes in here --> s and whatever other shapes in here --> 

Подключаем картинки на странице:

Всё картинки можно стилизовать через CSS (например задать заливку fill: black и т. д.). Замечу, что атрибут viewBox для символов нужно задавать обязательно, что-бы картинки правильно масштабировались (например если вы будете изменять их размеры).
Если вы используете grunt, взгляните в сторону grunt-svgstore: https://github.com/FWeinb/grunt-svgstore для автоматизации сборки картинок и обётки оных в один SVG контейнер.

Petroveg

Для разнообразия
Указание фрагмента SVG#ID работает везде при использовании в объектах с генерируемым контентом (img, embed, object).
Но указание фрагмента в url() для фона работает только в IE, FF). Про webkit сказано:
«Currently does not work for CSS background images in Chrome and Safari»

SVG (допустим, имя будет image.svg)

Если использовать картинки, то работает везде:

Единственный недостаток данного метода в том, что изображения полученные через background-image нельзя стилизовать.

Petroveg

Дмитрий Пыткин: Да, безусловно, всё оформление описано в SVG, а в CSS мы только выбираем view для отображения.
И то — с глюками webkit остаётся только использовать в картинках, что сводит к минимуму преимущество перед прямой вставкой SVG прямо в HTML (а в этом случае и кода меньше).

Petroveg

Дмитрий Пыткин: Да, спасибо, посмотрел. Нравится мне шрифтовое решение 2GIS, молодцы, хотя речь там о другом:)

Их выбор понятен, однако, base64 не даст стилизовать и вынудит каждый раз перекодировать SVG. Если количество файлов не критично, можно класть фоном в utf8, что даст возможность правок в CSS.

В последнем проекте я применял обе техники — и SVG в HTML для анимации, и SVG фоном в CSS.
А то, что описано в ответе. Я не применял, потому и снабдил заголовком «Для разнообразия»:)

Евгений Петров: я просто скинул посмотреть на то, какую методу использовали для реализации 2gis у себя. Судя по всему Base64 для решения проблем со скоростью рендеринга + можно пожать css в gzip. Меня смущает конечно то, что нельзя переиспользовать svg и стилизовать их, нужно будет поинтересоваться на этот счёт.
И по поводу фоновой загрузки, насколько я помню, svg графика добавленная на страницу после её загрузки через JS, не поддаётся её последующей стилизации через CSS. Возможно я ошибаюсь, тогда эта метода всех победит: osvaldas.info/caching-svg-sprite-in-localstorage

Petroveg

Дмитрий Пыткин: Конечно же SVG-фон стилизуется на этапе генерации CSS (параметры, выбор слоя etc.). Никто и не говорит о такой возможности:)

Использование — хорошая идея, за то вашему ответу поставил давно лайк:) Решение хранить файл SVG ИМХО относится к набору из десятков и сотен символов. Тут нужно тестировать расход ресурсов и трафика.

Источник

Оцените статью