- Can’t control SVG icon fill color with CSS styles
- 2 Answers 2
- currentColor
- Caching / performance consideration: SVG cloning
- fill property of SVG does not working in Chrome
- 2 Answers 2
- SVG Fill Color Not Working
- 7 Answers 7
- Not the answer you’re looking for? Browse other questions tagged css svg or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- SVG: заливка и обводка
- fill-rule
- fill-opacity
- stroke
- stroke-width
- stroke-linecap
- stroke-linejoin
- stroke-dasharray
- stroke-dashoffset
- stroke-opacity
- Can’t control SVG icon fill color with CSS styles
- 2 Answers 2
- currentColor
- Caching / performance consideration: SVG cloning
Can’t control SVG icon fill color with CSS styles
I have read all post in here about styling my svg fill color with CSS but without luck.
What I want is to able to make an icon with a link. My external svg file is grey, but I would like to make it red with css and change color to yellow when hovering.
I think I am targeting the SVG wrong. Please help. My test is here: testpage
2 Answers 2
Answer a little overdue, but worth having for reference for others.
Basically, the only type of SVG usage which can be used in conjunction with CSS is the inline usage.
This means you would literally put your SVG markup directly into the HTML source as follows:
NOTE: This SVG has been optimised using SVGO and then manually edited to include and ID
You can now control the SVG using CSS like so:
currentColor
You can also use the currentColor keyword in the SVG to apply a colour to certain elements of it, for example:
This can be handy if you need to use the same SVG across different websites / themes, such as dark and light, for easily switching SVG colours with CSS.
Caching / performance consideration: SVG cloning
You should also keep in mind, it’s not a good idea to use inline SVG for repetitive images, such as icons, because they can not be cached (the SVG code will be repeated throughout your HTML, increasing the ultimate file size).
Instead, one approach I like to use is to create an SVG index at the top of my page, which contains all the SVGs I want to use on the page, for example:
Make sure you set the SVG index to display: none so it doesn’t show up on the page.
You can now reuse these SVGs repetitively throughout the page using the xlink:href attribute as follows:
This is called cloning, and allows you to take advantage of cacheable SVGs which can be controlled with CSS!
Источник
fill property of SVG does not working in Chrome
Trouble is that I can’t set value (color) in fill property in Chrome, but in Firefox it works. I tried a lot ways to do it, but there is no result. The only way I see to change color of SVG icon is via jQuery (or JavaScript) by changing id of , which is below. Please help me solve this problem!
This is what I need to work in Chrome:
This is bad way to solve my problem which is not approriate for me.
2 Answers 2
Use currentcolor in the path fill attribute of the element.
The currentcolor keyword represents the value of an element’s color property. This lets you use the color value on properties that do not receive it by default.
Then, add a color CSS property to the class of the container that will wrap the instantiated by the element.
Not exactly a generic solution to the problem mentioned above, but I came here for a similar problem, where fill=»none» on an svg node doesn’t seem to work under all circumstances in both Chrome and Firefox, and potentially other browsers. This piece of SCSS fixes it for us, in our case for feather icons rendered via react-svgr:
The equivalent CSS, for the generic case:
Note that this may not cover all cases of SVG elements with fill properties and children with differently valued properties, so adapt to your needs.
Источник
SVG Fill Color Not Working
I’m new to using SVGs and can’t figure out what I’m doing wrong here. For most of them, if I want to change the color, I use:
But for this one — and other’s I’ve come across — for some reason this way doesn’t work.
7 Answers 7
you can just add !important beside fill
Your path has inline css on it with fill. This overrides your other css. Can be fixed with !important. Or you could remove the inline css.
If you are not in control of your SVG, (perhaps because it comes from an external source you are re-theming,) you are stuck using !important to override the SVG fill property.
If your SVG is in your code base, it is much better to set fill=»currentColor» , and then set the CSS color property.
As much as possible, try to avoid using !important . Instead, try to make your selectors more specific. Remember inline takes precedence over id , which takes precedence over classes, which takes precedence over elements.
Your solution may be as simple as adding an additional class, or in the case of a single element, an id .
For a more detailed explanation please read this article
If you have access to the svg internal code, just set the path to fill=»currentColor» and then set the regular color prop, not fill prop in the parent svg, eg:
I couldn’t get any display of CSS SVG until I discovered, quite by accident, that the quotation marks for an attribute value in SVG are not optional, as they are in HTML for values not containing spaces. Also, a hex value, like fill=»#00BB00″ , will not work for me, even using the fill=»currentColor» advice ( fill=»green» does work). Finally, if you use «url()» in the CSS, you can’t include newlines or omit the xmlns attribute.
Not the answer you’re looking for? Browse other questions tagged css svg or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.10.18.40487
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник
SVG: заливка и обводка
В SVG заливка и обводка имеют много разных интересных опций, которые предоставляют возможности гораздо шире того, что есть в CSS.
Например, можно нарисовать SVG-паттерн и использовать его не только в заливке, но и в обводке. Заливке и обводке можно указывать разную прозрачность, также можно управлять пунктирной обводкой, на чем можно построить интересные анимированные эффекты.
В качестве заливки и обводки можно задавать none , цвета, ключевые слова ( currentColor и transparent ), а также градиенты и паттерны.
Возможные значения: none , ключевые слова, цвета, паттерны и градиенты. Значение по умолчанию — black .
fill-rule
Свойство определяет как будут заливаться сложные фигуры, имеющие пересечения внутри себя. Для простых фигур ни на что не влияет.
Возможные значения: nonzero , evenodd
fill-rule=»nonzero» интересно ведет себя для фигур из двух путей. Например, если внешний круг нарисован по часовой стрелке, а внутренний в обратном направлении, центральный круг останется без заливки (слева). Если же оба круга нарисованы в одном направлении — фигура зальется полностью (справа):
fill-opacity
Управление прозрачностью заливки. Можно задавать значения от 0.0 до 1.0 или в процентах. Правда, Firefox не любит значения в процентах для градиентов (пруфлинк, смотреть в FF).
stroke
Цвет обводки. Значения по умолчанию нет.
stroke-width
Толщина обводки, можно задавать в единицах длины или в процентах. Значение по умолчанию: 1.
stroke-linecap
Свойство определяет как будут выглядеть концы линий. Возможные значения: butt , round , square . Значение по умолчанию: butt .
stroke-linejoin
Определяет как будут выглядеть соединения линий на углах. Возможные значения: miter , round , bevel . Значение по умолчанию: miter .
stroke-dasharray
Управляет видом пунктирной обводки. Можно задавать в единицах длины или в процентах. Если задано одно значение, второе значение считается равным первому. Например, stroke-dasharray=»1″ нарисует линию из отрезков длиной одну единицу разделенных пробелами такой же ширины.
Примеры разных пунктирных линий:
Используя обводку и простые фигуры можно получить удивительные вещи:
Также stroke-dasharray интересно сочетается с анимацией:
stroke-dashoffset
Свойство позволяет задать смещение пунктирной обводки относительно первоначального положения. Значение задается в единицах длины или в процентах, значения могут быть отрицательными. Значение по умолчанию: 0.
В этом примере оранжевые и желтые линии смещены относительно красной с помощью разных значений stroke-dashoffset :
Сочетая stroke-dashoffset и stroke-dasharray можно получить интересные эффекты.
Для полноценного просмотра воспользуйтесь браузерами на Webkit. Ссылка на полную версию.
Для перезапуска нажмите Rerun.
Несколько вдохновляющих ссылок про анимацию на stroke-dashoffset :
stroke-opacity
Прозрачность обводки. Задаются значения от 0.0 до 1.0.
Анимация обводки позволяет получить совершенно удивительные вещи. Правда, я в своих примерах использовала CSS (и это демо не играет в Firefox) и SVG-анимацию, которая работает таки везде, но задается странно, длинно и неудобно. Думаю, что оптимальнее всего для анимации SVG использовать JavaScript-библиотеки.
Источник
Can’t control SVG icon fill color with CSS styles
I have read all post in here about styling my svg fill color with CSS but without luck.
What I want is to able to make an icon with a link. My external svg file is grey, but I would like to make it red with css and change color to yellow when hovering.
I think I am targeting the SVG wrong. Please help. My test is here: testpage
2 Answers 2
Answer a little overdue, but worth having for reference for others.
Basically, the only type of SVG usage which can be used in conjunction with CSS is the inline usage.
This means you would literally put your SVG markup directly into the HTML source as follows:
NOTE: This SVG has been optimised using SVGO and then manually edited to include and ID
You can now control the SVG using CSS like so:
currentColor
You can also use the currentColor keyword in the SVG to apply a colour to certain elements of it, for example:
This can be handy if you need to use the same SVG across different websites / themes, such as dark and light, for easily switching SVG colours with CSS.
Caching / performance consideration: SVG cloning
You should also keep in mind, it’s not a good idea to use inline SVG for repetitive images, such as icons, because they can not be cached (the SVG code will be repeated throughout your HTML, increasing the ultimate file size).
Instead, one approach I like to use is to create an SVG index at the top of my page, which contains all the SVGs I want to use on the page, for example:
Make sure you set the SVG index to display: none so it doesn’t show up on the page.
You can now reuse these SVGs repetitively throughout the page using the xlink:href attribute as follows:
This is called cloning, and allows you to take advantage of cacheable SVGs which can be controlled with CSS!
Источник