Change icon color html

Change Color of SVG on Hover

There are a lot of different ways to use SVG. Depending on which way, the tactic for recoloring that SVG in different states or conditions — :hover , :active , :focus , class name change, etc. — is different. Let’s look at the ways.

Inline SVG is my favorite way to use SVG anyway, in part because of how easy it is to access and style the SVG. See the Pen
bJXNyy by Chris Coyier (@chriscoyier)
on CodePen. If you’re used to working with icon fonts, one thing you might enjoy about them is how easy it is to change the color. You’re largely limited to a single color with icon fonts in a way that SVG isn’t, but still, it is appealingly easy to change that single color with color . Using inline SVG allows you to set the fill , which cascades to all the elements within the SVG, or you can fill each element separately if needed.

  • The internal SVG elements (like the ) can have no fill themselves. This allows the fill set from the parent SVG to cascade into the Shadow DOM created by . As soon as you have something like in the , you’ve lost outside CSS control.
  • Likewise, the fill of individual elements cannot be controlled within the SVG like you could with inline SVG. This means you’re pretty firmly in single-color territory. That covers most use cases anyway, but still, a limitation nonetheless.
Читайте также:  Java set field by name

SVG can be set as a background image just like PNG, JPG, or whatever other graphics format. At this point, you’ve sort of given up on being able to change the fill . One possibility, which I’d argue isn’t a particularly good one, is to have two versions of every icon, in the respective colors, and swap between them:

I don’t blame you if you’d rather not swap sources, so another possibility is to get gnarly with filters.

Trying to finagle the right filters to get the color right is tricky stuff. Fortunately, Barrett Sonntag made a tool to calculate the filters for you! Turning black to red ends up a whacky combination like this: invert(27%) sepia(51%) saturate(2878%) hue-rotate(346deg) brightness(104%) contrast(97%); .

SVG also has object , which is kinda neat in that it had a built-in fallback back in the day — although browser support is so good these days, I honestly have never used it. But if you’re using it, you would probably have to use this filter technique to swap color on hover.

Use a mask instead of a background image

This way, the SVG is still in charge of essentially drawing the shape, but the color comes from the background-color (or image! or gradient!) behind it rather than the SVG itself.

SVG background images as data URLs

This doesn’t change that much from above, but it does open up one interesting possibility: Using a variable for the internal fills. Here that is with Sass keeping the URLs as variables:

Источник

Как изменить цвет SVG в CSS

В этой статье рассмотрим несколько примеров, как задать цвет любому изображению в формате svg с использованием css-стилей.

Есть множество вариантов, как использовать SVG. От того, как вы применяете SVG и будет зависеть способы редактирования.

Основы

SVG (Scalable Vector Graphic) — масштабируемая векторная графика. Это уникальный формат для изображений. В отличии от привычных нам форматов, в svg не используются пиксели. Здесь картинка строется на векторах. Это значит, что вы можете, например, масштабирать размер картинки до любых значений и при этом не терять качество.

Изображение svg можно вставить кодом прямо в файл html — это будет инлайновый вариант:

А можно вставить через тег img:

Если заглянуть «под капот» и изучить код, который отвечает за отрисовку SVG, то можно выделить два свойства, которые отвечают за цвет — fill (заливка) и stroke (обводка). Их можно редактировать и тем самым менять цвет иконки.

Давайте выделим несколько методов, которые позволяют менять цвет SVG.

1. Меняем цвет с помощью свойства fill

Смотрите, у нас два квадрата — они идентичны, за исключением свойства fill. В одном случае мы залили квадрат красным цветом, в другом вообще не прописали это свойство.

Свойство fill можно применять к отдельному вектору в вашем изображении.

2. Меняем цвет в файле style.css

Или в любом другом файле css, который подключен к html.

Источник

Подключаем 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 .
  • В следующей статье продолжим работу с тегам , , разберем как можно ещё кастомизировать векторную графику.

Источник

How to Change the Color of Icons with CSS

On almost every website there are icons that change color when you hover over them or activate a function. The good old way to achieve this is to swap images. To do this, we need to create two images with the same icon but different colors and swap them with javascript:

How to Do This with CSS and Background Images

Use a or or any other element of your choice and set a background image:

html:
CSS:
.my_image width: 100px;
height: 100px;
background-image: url(my_image.png);
background-repeat: no-repeat;
background-position: center;
>
.my_image:hover background-image: url(my_image_active.png);
>

We still need two images, but the code is much simpler.

Changing Between More than Two Colors

The methods I’ve shown work well, but what if we need to use three or even more colors for our icons? Just think about websites where users can choose between multiple color themes. Sure, we can create many images and every time a client wants to change them, we can recreate all the images.

But what if we could achieve this with a simple CSS background color instead?

First, we make the image transparent and simply fill its background with, say, white.

HTML:CSS:
#my_image (
background-color: red;
>
#my_image:hover (
background-color: blue;
>

What If the Background Color of Our Page Changes?

While working on my last project, I was faced with this problem. I created a website that simulates a mobile app for B2B customers.

The customers should be able to match the colors of each app element to their corporate design. Once all the colors are fixed, the app developers copy the color codes into the app source code to compile it.

This way, the color of the icons and background can be customized to any of our more than 16 million values. My task was to find a solution that would cover all options. After a lot of thinking, I found the solution:

SVG is the a Answer!

All you have to do is embedd the SVG code into your HTML and give it a CSS class name and use CSS property “fill”:

HTML:




CSS:
.myIcon fill: red;
>

Now you can use javascript to change the color value, eg. with a color picker or your own script.

Note: this doesn’t work if you use an IMG tag for the SVG. You can’t change the SVGs color if you do it this way:

Another Way to Change Icon Color

If you have a font set for your icons, for example the Awesome font or the Googles Material font, it’s very simple: include the font and the corresponding style sheet and paste the code for the icon into your HTML:

HTML: 
CSS:
. fa-my-icon color: red;
>

Hope you can use one of the options shown here for your own web projects.

Источник

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