How to change svg color css

How to change svg color css

Подключаем SVG-иконку на сайт и меняем цвет через CSS

В предыдущих сериях…

В прошлой статье мы выяснили, в чем отличие растровых форматов изображения от векторных. Теперь будем работать с векторной графикой. Для начала, научимся подключать эти изображения разными способами.

Подключение через тег в html

How to change svg color css. Смотреть фото How to change svg color css. Смотреть картинку How to change svg color css. Картинка про How to change svg color css. Фото How to change svg color css

Можно подключить svg-графику в качестве фона элемента. Часто используются фоновые паттерны. Это небольшой фрагмент, впоследствии повторяющийся и создающий орнамент.

Так выглядит наш паттерн:

How to change svg color css. Смотреть фото How to change svg color css. Смотреть картинку How to change svg color css. Картинка про How to change svg color css. Фото How to change svg color css

Вот, что у нас получилось:

How to change svg color css. Смотреть фото How to change svg color css. Смотреть картинку How to change svg color css. Картинка про How to change svg color css. Фото How to change svg color css

Описываем svg-графику inline

Существуют специальные теги и атрибуты для описания графики прямо в коде. При этом, изображение становится интерактивным — мы можем, например, менять цвет, или размер по наведению на иконку.

Тег используется как контейнер для хранения SVG графики. При помощи тега

и его атрибутов создается фигура. Посмотрите, как выглядит иконка YouTube в inline формате.

Взгляните на результат:

How to change svg color css. Смотреть фото How to change svg color css. Смотреть картинку How to change svg color css. Картинка про How to change svg color css. Фото How to change svg color css

Заключение

, разберем как можно ещё кастомизировать векторную графику.

How to change color of SVG (Various ways using CSS)

In one of the previous articles, I have mentioned Best 5+ Free HTML Rich Text Editor to use but now in this article, I have provided few possible ways to change the color of SVG images using CSS or Javascript.

If you are using SVG image icons or SVG image logo and want to change the color of the image, then you can have an issue while changing its color, because if you will use CSS property like background-color or color for SVG files it will not work, so I have provided solutions to resolve this issue.

Change SVG color using CSS

Every SVG has XML file like structure so, it could be as below

So, if you want to change SVG color, then you can directly target » path » element or » polygon » element of SVG structure and use CSS property » fill «

So, you can have CSS has below

How to change svg color css. Смотреть фото How to change svg color css. Смотреть картинку How to change svg color css. Картинка про How to change svg color css. Фото How to change svg color css

Here is the complete Fiddle sample

But the above solution will only work when you have SVG with path information.

You can also open SVG in any Text Editor and then get to it’s XML as shown above and then in

tag use property «fill» to add change color, as shown below

Another way (Using SVG as background image)

You can also use SVG as a background image for an icon and then use CSS ‘mask’ property to fill it as Background.

Once you have set it as the background image, you can simply use ‘background-color’ CSS property to change image’s color

With Sample HTML

Gives output as below

How to change svg color css. Смотреть фото How to change svg color css. Смотреть картинку How to change svg color css. Картинка про How to change svg color css. Фото How to change svg color css

Using Filter and SVG inside IMG tag

If you are using SVG with IMG tag, you can use CSS property ‘filter’ with saturation, which will change the color of the SVG image

Here is the fiddle

That’s it, these are some 3 useful ways to change color of SVG using CSS.

How to change color of SVG image using CSS (jQuery SVG image replacement)?

This is a self Q&A of a handy piece of code I came up with.

Currently, there isn’t an easy way to embed an SVG image and then have access to the SVG elements via CSS. There are various methods of using JS SVG frameworks, but they are overly complicated if all you are doing is making a simple icon with a rollover state.

So here is what I came up with, which I think is by far the easiest way to use SVG files on a website. It takes its concept from the early text-to-image replacement methods, but as far as I am aware has never been done for SVGs.

This is the question:

How do I embed an SVG and change its color in CSS without using a JS-SVG framework?

How to change svg color css. Смотреть фото How to change svg color css. Смотреть картинку How to change svg color css. Картинка про How to change svg color css. Фото How to change svg color css

18 Answers 18

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

Firstly, use an IMG tag in your HTML to embed an SVG graphic. I used Adobe Illustrator to make the graphic.

This is just like how you’d embed a normal image. Note that you need to set the IMG to have a class of svg. The ‘social-link’ class is just for examples sake. The ID is not required, but is useful.

Then use this jQuery code (in a separate file or inline in the HEAD).

What the above code does is look for all IMG’s with the class ‘svg’ and replace it with the inline SVG from the linked file. The massive advantage is that it allows you to use CSS to change the color of the SVG now, like so:

The jQuery code I wrote also ports across the original images ID and classes. So this CSS works too:

How to change svg color css. Смотреть фото How to change svg color css. Смотреть картинку How to change svg color css. Картинка про How to change svg color css. Фото How to change svg color css

You can now use the CSS filter property in most modern browsers (including Edge, but not IE11). It works on SVG images as well as other elements. You can use hue-rotate or invert to modify colors, although they don’t let you modify different colors independently. I use the following CSS class to show a «disabled» version of an icon (where the original is an SVG picture with saturated color):

This makes it light grey in most browsers. In IE (and probably Opera Mini, which I haven’t tested) it is noticeably faded by the opacity property, which still looks pretty good, although it’s not grey.

Here’s an example with four different CSS classes for the Twemoji bell icon: original (yellow), the above «disabled» class, hue-rotate (green), and invert (blue).

How to change svg color css. Смотреть фото How to change svg color css. Смотреть картинку How to change svg color css. Картинка про How to change svg color css. Фото How to change svg color css

How to change svg color css. Смотреть фото How to change svg color css. Смотреть картинку How to change svg color css. Картинка про How to change svg color css. Фото How to change svg color css

If you can include files (PHP include or include via your CMS of choice) in your page, you can add the SVG code and include it into your page. This works the same as pasting the SVG source into the page, but makes the page markup cleaner.

You just have to use a CSS rule like this:

I’m assuming you have html something like this:

Definitely go the filter route, ie. your svg is most likely black or white. You can apply a filter to get it to be whatever color you want, for example, I have a black svg that I want mint green. I first invert it to be white (which is technically all RGB colors on full) then play with the hue saturation etc. To get it right:

Even better is that you could just use a tool to convert the hex you want into a filter for you: https://codepen.io/sosuke/pen/Pjoqqp

@Drew Baker gave a great solution to solve the problem. The code works properly. However, those who uses AngularJs may find lots of dependency on jQuery. Consequently, I thought it is a good idea to paste for AngularJS users, a code following @Drew Baker’s solution.

AngularJs way of the same code

1. Html: use the bellow tag in you html file:

2. Directive: this will be the directive that you will need to recognise the tag:

4. Unit-test with karma-jasmine:

It could save a ton of ugly script. Sorry if it’s off-base, but sometimes the simple solutions can be overlooked.

. even swapping multiple svg images might be smaller in size than some of the code snippets for this question.

It replaces the SVG element after it’s been rendered, and places it inside a div element, making its CSS easily changeable. This helps using the same SVG file in different places using different sizes/colors.

The usage is simple:

After that, you can easily have:

How to change svg color css. Смотреть фото How to change svg color css. Смотреть картинку How to change svg color css. Картинка про How to change svg color css. Фото How to change svg color css

Here’s a version for knockout.js based on the accepted answer:

Important: It does actually require jQuery too for the replacing, but I thought it may be useful to some.

Then just apply data-bind=»svgConvert: true» to your img tag.

This solution completely replaces the img tag with a SVG and any additional bindings would not be respected.

There is an open source library called SVGInject that uses the onload attribute to trigger the injection. You can find the GitHub project at https://github.com/iconfu/svg-inject

Here is a minimal example using SVGInject:

After the image is loaded the onload=»SVGInject(this) will trigger the injection and the element will be replaced by the contents of the SVG file provided in the src attribute.

It solves several issues with SVG injection:

SVGs can be hidden until injection has finished. This is important if a style is already applied during load time, which would otherwise cause a brief «unstyled content flash».

The elements inject themselved automatically. If you add SVGs dynamically, you don’t have to worry about calling the injection function again.

A random string is added to each ID in the SVG to avoid having the same ID multiple times in the document if an SVG is injected more than once.

SVGInject is plain Javascript and works with all browsers that support SVG.

Disclaimer: I am the co-author of SVGInject

How to set a External SVG color in HTML using CSS? [duplicate]

I am trying to use SVG on my web page.

But it’s color is black. So, I want it to be changed. So, I have done-

To import heart_border.svg file and make its color red. But it does not work as you see i the output.

Can anyone help me please to solve this?

Thank you very much in advance for helping.

How to change svg color css. Смотреть фото How to change svg color css. Смотреть картинку How to change svg color css. Картинка про How to change svg color css. Фото How to change svg color css

5 Answers 5

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

CSS does not apply cross document and you’ve two documents here heart_border.svg and the container html document.

Alternatively if you add the SVG inline in the html document itself so that you only have one document the CSS will then apply.

This thread is old but I wanted to share my solution, based on SVG filters. You just need to define a feColorMatrix filter as you want and apply it to the external image. See example below for more details.

Compatible with any browsers that can handle SVG.

With your current code you set the fill on the object element.

Instead, you need to set it on the svg element.

Something like this:

The problem is that you don’t target the actual SVG element, you target the «SVG container». To be able to change the color of one of the elements inside the SVG you have to target that specific element.

E.g change the fill color of all paths in a SVG:

If you want to make it easier to handle add class names to the different elements inside the svg.

This will make it possible to target a specific element by its class:

Do you really need SVG to be external file? you might want to put svg locally once in document.

Делаем разноцветные иконки с помощью SVG-символов и CSS-переменных

How to change svg color css. Смотреть фото How to change svg color css. Смотреть картинку How to change svg color css. Картинка про How to change svg color css. Фото How to change svg color css

Давно прошли те дни, когда для иконок в вебе использовались картинки и CSS-спрайты. С развитием веб-шрифтов номером 1 для отображения иконок на сайтах стали иконочные шрифты.

Шрифты — векторные, так что вам не нужно беспокоиться о разрешении экрана. Для них можно использовать те же CSS-свойства, что и для текста. В результате вы имеете полный контроль над их размером, цветом и стилем. Вы можете добавлять к ним эффекты, трансформировать или декорировать их. Например, повернуть ( rotate ), подчеркнуть ( underline ) или добавить тень ( text-shadow ).

Иконочные шрифты не идеальны, поэтому все большее число людей предпочитает использовать встроенные SVG-изображения. На CSS Tricks есть статья, где описаны моменты, в которых иконочные шрифты уступают SVG-элементам: резкость, позиционирование, сбои кросс-доменной загрузки, особенности браузеров и блокировщики рекламы. Сейчас вы можете обойти большинство этих проблем, что, в целом, делает использование иконочных шрифтов безопасным.

Да, еще одна вещь, которая абсолютно невозможна при использовании иконочных шрифтов: поддержка многоцветности. Только SVG может это сделать.

TL;DR: этот пост позволяет вникнуть в то, как и почему. Если вы хотите понять весь процесс, читайте дальше. В противном случае вы можете посмотреть окончательный код на CodePen.

Настройка символов SVG-иконок

Проблема встроенных SVG в том, что они сложны. Вы не хотите копипастить все эти координаты каждый раз, когда нужно использовать одну и ту же иконку. Получится повторяющийся, трудно читаемый и тяжело поддерживаемый код.

Использование SVG-символов позволяет иметь лишь один экземпляр каждого SVG-элемента и использовать его где угодно с помощью ссылки.

Полная разметка SVG-элемента пишется один раз и скрывается.

Получится точная копия вашей оригинальный SVG-иконки.

How to change svg color css. Смотреть фото How to change svg color css. Смотреть картинку How to change svg color css. Картинка про How to change svg color css. Фото How to change svg color css

Вот она! Довольна милая, правда?

Вы вероятно заметили атрибут xlink:href — это и есть ссылка между вашей иконкой и оригинальным SVG-изображением.

Для безопасности используйте оба атрибута.

Добавление цвета

В отличие от шрифтов, свойство color не действует на SVG-иконки: необходимо использовать атрибут fill для указания цвета. Это значит, что они не наследуют родительский цвет текста, но вы все равно можете стилизовать их через CSS.

А следовательно, вы можете создавать другие экземпляры этой же иконки разных цветов.

Это работает, но это не совсем то, что мы хотим. Все, что мы сделали до сих пор, можно сделать и с помощью обычного иконочного шрифта. То, что мы хотим, — это сделать каждую часть иконки разного цвета. Мы хотим залить разными цветами каждую часть одной иконки, не изменяя другие ее экземпляры, и мы хотим, чтобы было возможно переопределять эти цвета при необходимости.

Сначала у вас может возникнуть идея положиться на специфичность.

И что нам тогда делать? Как мы можем повлиять на содержимое детей, когда говорят, что детей нет в DOM?

CSS-переменные помогут

CSS-переменные объявляются в наборах правил так же, как и любое другое свойство. Вы можете назвать их как хотите и присвоить им любое допустимое CSS значение. Затем вы определите через эту переменную значение свойства самого элемента или его ребенка, и оно будет наследоваться.

Теперь давайте применим эту концепцию для нашего SVG-символа. Мы будем использовать атрибут fill для каждой части path в определении нашей SVG-иконки и зададим им разные CSS-переменные. Затем мы назначим им разные цвета.

How to change svg color css. Смотреть фото How to change svg color css. Смотреть картинку How to change svg color css. Картинка про How to change svg color css. Фото How to change svg color css

С этого момента все, что нам нужно для создания копии с другой цветовой схемой, это написать новый класс.

Свойство fill будет работать, потому что атрибут fill исходного SVG задан с неопределенными значениями CSS-переменных.

Как назвать мои CSS-переменные?

Проблема в том, что в нашем случае мы не можем применять атомные классы к элементам, которые хотим стилизовать. Принципы utility-first не применимы, так как у нас есть только ссылка для каждой иконки, а мы должны стилизовать ее через вариации классов.

По умолчанию или не по умолчанию

Заманчивая идея — сделать ваши иконки по умолчанию разноцветными. В этом случае вы сможете использовать их без дополнительной стилизации, и только в случае необходимости добавлять отдельный класс.

Добиться этого можно двумя способами: через :root или через var() default.

var() default

Установка значений по умолчанию может быть полезна, но это компромисс. Я предлагаю не привыкать к этому, и делать только тогда, когда это имеет смысл для конкретного проекта.

Как это все поддерживается браузерами?

CSS-переменные поддерживаются всеми современными браузерами, но, как вы вероятно догадались, IE не поддерживает их, совсем. Даже IE11, и поскольку его развитие было прекращено в пользу Edge, нет никаких шансов, что он когда-либо будет их поддерживать.

Но только из-за того, что переменные не работают в браузере, который вам нужно поддерживать, не значит, что вы должны полностью от них отказаться. В таких случаях используйте graceful degradation: предлагайте разноцветные иконки современным браузерам, а для старых указывайте запасной цвет.

Все, что вам нужно сделать, — это добавить определение цвета, которое будет работать только, если CSS-переменные не поддерживаются. Этого можно добиться, указав свойству fill резервный цвет. Если CSS-переменные поддерживаются, это объявление не будет учтено. Если же это не так, оно сработает.

Теперь можно определять цветовые схемы, не беспокоясь о поддержке браузеров.

Передача CSS-переменных в mixin через @content необязательна. Если вы сделаете это снаружи, скомпилированный CSS будет таким же. Но может быть полезно держать все это в одном месте.

Вы можете проверить этот пример в разных браузерах. В последних версиях Firefox, Chrome и Safari последние две чашки будут соответственно красной с серым паром и синей с серым паром. В Internet Explorer и Edge ниже 15 версии третья иконка будет вся красная, а четвертая — вся синяя.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *