Css вставить svg before

CSS :before on inline SVG

Icons by default have classes svg-inline—fa and fa-w-*.,To extend further this topic. In case you want to add Font Awesome 5 icons you need to add some extra CSS.,There are also modifier classes like fa-lg, fa-rotate-* and other. You need to check svg-with-js.css file and find proper CSS for that., How to get names of the files which contain the specified text only

And my test.svg looks like this:

Answer by River Roach

Method 2: Using the content property: The content property in CSS is used to conveniently generate content dynamically on a page. We can add the SVG content using this property on an empty pseudo-element. The other CSS properties help to position and size the content properly.,Method 1: Using the background-image property: The background-image property is used to set one or more background images to an element. We can also add the SVG content using this property and leaving the content property empty. The other CSS properties help to position and size the content properly.,The :before and :after pseudo-elements allow one to add styling to the webpage without adding unnecessary markup. SVG content can be added using these pseudo-elements by following the methods described below:,Set the opacity only to background color not on the text in CSS

Answer by Steven Cox

I try to add SVG code into pseudo element, Need help How to do it without an error.,I try to add SVG code into pseudo element,,Is there any free tool to store SVG into file?,How to solve this error? Line 1 : Start tag expected, ‘

I try to add SVG code into pseudo element, Need help How to do it without an error.

Answer by Willie Liu

Update Thanks porneL for pointing out the relation between generated content and replaced elements. I found this article which deals with this very topic: http://red-team-design.com/css-generated-content-replaced-elements/,No, inline SVG is treated as an image, and images are replaced elements which are not allowed to have generated content.,The content CSS property is used with the ::before and ::after pseudo-elements to generate content in an element. Objects inserted using the content property are anonymous replaced elements. before creates a pseudo-element that is the first child of the element matched. Often used to add cosmetic content to an element, by using the content property. This element is inline by default.

 svg < left: 50px; position: absolute; top: 50px; >svg circle < fill: green; >svg:before < border: 2px solid blue; content: ""; height: 100px; margin: -6px; padding: 4px; position: absolute; width: 100px; z-index: -1; >div < background-color: green; height: 100px; left: 200px; position: absolute; top: 150px; width: 100px; >div:before
 svg < left: 50px; position: absolute; top: 50px; > svg circle < fill: green; >svg:before < border: 2px solid blue; content: ""; height: 100px; margin: -6px; padding: 4px; position: absolute; width: 100px; z-index: -1; > div < background-color: green; height: 100px; left: 200px; position: absolute; top: 150px; width: 100px; > div:before < border: 2px solid blue; content: ""; height: 100px; margin: -6px; padding: 4px; position: absolute; width: 100px; z-index: -1; >

Answer by Kody Dunn

For adding icons into css pseudo-element you need to set some size and content with SVG. Ie:,There is the second option of using SVG in pseudo-element, but this will not work on IE because it is not supporting mask-size property:

Читайте также:  New if else java

For adding icons into css pseudo-element you need to set some size and content with SVG. Ie:

.icon-one:after < content: url('data:image/svg+xml;charset=utf-8,') display: inline-block; height: 20px; width: 20px; >

There is the second option of using SVG in pseudo-element, but this will not work on IE because it is not supporting mask-size property:

.icon-two:after < content: ''; -webkit-mask: url('data:image/svg+xml;charset=utf-8,') no-repeat 50% 50%; mask: url('data:image/svg+xml;charset=utf-8,') no-repeat 50% 50%; -webkit-mask-size: cover; mask-size: cover; display: inline-block; height: 20px; width: 20px; >

For changing color we’re using background-color property.

Answer by Julio Snyder

The content property in CSS is used in conjunction with the pseudo-elements ::before and ::after. It is used to literally insert content. There are four value types it can have.,I just want to know how we can make the text in content property to be displayed as two or more line, for example:,Presentation about pseudo-elements,Just add a span around your input element and give it the asterisk class instead of the input. Since ::before + ::after add the content before/after the elements own content and input elements don’t have content, your example doesn’t work.

Then an element like this:

Источник

How to Add a Svg as Content on: Before Pseudo Element of an Element

How can I add a svg as content on :before pseudo element of an element?

Seems like the SVG tag needed more attributes.

#square< background-color: green; width: 100px; height: 100px;>
#square:before< display: block; content: url("data:image/svg+xml;charset=UTF-8, "); background-size: 28px 28px; height: 28px; width: 28px;>

Is there a way to use SVG as content in a pseudo element ::before or ::after

Yes you can! Just tested this and it works great, this is awesome!

#test::before content: url(path/to/your.svg); 
width: 200px;
height: 200px;
>

Or if you prefer to put the SVG directly in the CSS:

#test::before content: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3Ccircle cx='100' cy='50' r='40' stroke='black' stroke-width='2' fill='red'/%3E%3Cpolyline points='20,20 40,25 60,40 80,120 120,140 200,180' style='fill:none;stroke:black;stroke-width:3'/%3E%3C/svg%3E "); 
width: 200px;
height: 200px;
>

Use SVG image inline inside CSS :before pseudo-element

div::before content: ''; 
background-image: url('data:image/svg+xml;charset=US-ASCII,%3Csvg%20width%3D%22auto%22%20height%3D%2210%22%20viewBox%3D%220%200%2080%2020%22%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%3E%3Cpath%20d%3D%22M0%200h20L10%2020z%22%20fill%3D%22%23ff0%22/%3E%3Cpath%20d%3D%22M30%2020h20L40%200z%22/%3E%3Cpath%20d%3D%22M60%200h20L70%2020z%22%20fill%3D%22%23ff0%22/%3E%3C/svg%3E');
>

I use http://www.grumpicon.com/ this website to convert SVGs for CSS background

Читайте также:  Php дней часов минут секунд

CSS :before on inline SVG

No, inline SVG is treated as an image, and images are replaced elements which are not allowed to have generated content.

Strictly speaking, I think it’s undefined. CSS 2.1 just talks about «images, embedded documents and applets» in general and The HTML standard defines it for images, but not SVG explicitly.

IE not displaying SVG as content in a pseudo element :before or :after

I have tested it with IE 11 and I am able to produce the issue. It seems that the pseudo-elements content attribute do not currently work on SVG elements. It can be possible that it is some kind of bug or it is IE browser default behavior. I will try to submit the feedback regarding this issue.

As a workaround, I suggest you display the svg content using background-image attribute, like this:

.div1:after content: »;
display: block;
height: 80px;
width: 80px;
background-image: url(data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20version%3D%221.1%22%20height%3D%2280%22%20width%3D%22160%22%3E%0D%0A%20%20%3Ccircle%20cx%3D%2240%22%20cy%3D%2240%22%20r%3D%2238%22%20stroke%3D%22black%22%20stroke-width%3D%221%22%20fill%3D%22red%22%20%2F%3E%0D%0A%20%20%3Ccircle%20cx%3D%22120%22%20cy%3D%2240%22%20r%3D%2238%22%20stroke%3D%22black%22%20stroke-width%3D%221%22%20fill%3D%22blue%22%20%2F%3E%0D%0A%3C%2Fsvg%3E);
>

The result in IE 11 browser as below:

Sample Image

I am not able to use my svg with background-image property whereas
your svg is loading with the property. Is there any problem with my
svg?

When we use SVG with background-image property, we should ensure that reserved URL characters are encoded (e.g. < === %3C and >=== %3E ) and also replace the space with ‘%20’.

So, please encode your svg element as below:

background-image: url(data:image/svg+xml,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%20preserveAspectRatio%3D%22xMidYMid%20meet%22%20viewBox%3D%22266.53926701570674%20152.66492146596858%2044%2044%22%3E%3Cdefs%3E%3Cpath%20d%3D%22M267.54%20153.66L307.54%20193.66L267.54%20193.66L267.54%20153.66Z%22%20id%3D%22d6AN4MEUYO%22%3E%3C%2Fpath%3E%3C%2Fdefs%3E%3Cg%3E%3Cg%3E%3Cuse%20xlink%3Ahref%3D%22%23d6AN4MEUYO%22%20opacity%3D%221%22%20fill%3D%22red%22%20fill-opacity%3D%221%22%3E%3C%2Fuse%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E);

Then, the result like this:

Sample Image

CSS — SVG in a pseudo element with Color changing capabilities

This is easy if you flip the logic — instead of adding color on the hover — think of it as removing color when you are not hovering.

With CSS filters — you can convert your svg to greyscale — meaning that a color image / SVG is rendered as a black and white image. Then on hover — stop the filter / conversion and your svg will have its actual color.

Note that this only works with one color change — you cannot have different paths go different colors etc — but by reversing the color logic you get a black and white svg that turns colorful on hover.

The following div has a border — just to show the dimensions (and I would probably do the svg as the background image of the div rather than the ::before — but I left it as requested. The SVG is iniitally shown as black and on hover over the div — the svg turns red. magic 🙂

div height: 160px; 
width: 300px;
border: solid 1px blue;
position: relative
>

div::before content: url('data:image/svg+xml;utf8, ');
display: block;
-webkit-filter: grayscale(100);
filter: grayscale(100);
>


div:hover:before -webkit-filter: grayscale(0);
filter: grayscale(0);
>

Add svg to content property

Absolutely, I use this (or rather a variant of it) all the time:

Читайте также:  Css отступы при печати

Источник

Векторная замена спрайтам — имплантируем SVG в CSS

Не так давно компания, в которой я работаю, наконец-то окончательно отказалась от поддержки IE8 и, как следствие, я вплотную занялся вопросом перехода с растровых иконок на векторные. Основные плюсы SVG — это масштабирование, малый вес и возможность стилизации через CSS.

  • Масштабирование. При произвольных размерах элементов спрайта для того, чтобы его точно отпозиционировать, приходится танцевать с бубном. И при изменении размера самого спрайта (например, при добавлении нового элемента) все может поползти.
  • Возможность стилизации посредством CSS отсутствует, потому что физически SVG-картинки в HTML-коде нет.

Возьмем, к примеру, иконку корзины:

image

Ее код выглядит примерно так:

Соответственно, использование ее в качестве фона в data-uri будет выглядеть так:

.element_whis_svg_background < background: url('data:image/svg+xml;utf8,. '); > 

Пробуем. В Хроме и Опере все замечательно, а вот в IE9-10-11, Safari, и, как ни странно, Firefox — фоновая картинка не отображается, они не понимают такой формат записи. Лезем искать, в чем проблема и выясняем, что для IE и прочих для содержимого SVG-файла надо выполнить URI-кодирование строки по стандарту RFC 3986. Кодируем, получаем вот такую конструкцию:

%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%201850%201635%22%3E%3Cg%20fill%3D%22%23101010%22%3E%3Cpath%20d%3D%22M1254%201163H51c-26%200-51-25-51-51V981c0-23%2022-51%2051-51h1075c22%200%2036-13%2044-30l96-192c4-9%201-12-8-12H51c-22%200-51-25-51-51V514c0-23%2023-51%2051-51h1298c27%200%2046-13%2056-33l200-401c9-18%2020-29%2041-29h182c19%200%2029%207%2018%2029l-554%201111c-5%2010-19%2023-38%2023z%22%2F%3E%3Ccircle%20cx%3D%22207%22%20cy%3D%221453%22%20r%3D%22181%22%2F%3E%3Ccircle%20cx%3D%221062%22%20cy%3D%221453%22%20r%3D%22181%22%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E 

Подставляем ее в background, проверяем:

.element_whis_svg_background < background: url('data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2 . svg%3E'); >

Ура, все работает! Нюанс — кодировку в данном случае указывать не нужно. Если указать — то перестанет работать в IE.

Ну и, наконец, для того, чтобы внешний вид иконки можно было настраивать, используем любой препроцессор (я использую LESS, но это не принципиально) и оформим наш класс иконки как примесь (mixin). Для того, чтобы можно было менять цвет заливки, находим в кодированной строке атрибут fill, там будет что-то типа:

То, что находится между %23 и %22 — и есть искомый код цвета, на место которого надо подставить переменную. В итоге получим следующее:

.icon__cart(@width, @height, @fill) < content: ''; display: block; width: @width; height: @height; background-size: contain; background-repeat: no-repeat; background: url('data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%201850%201635%22%3E%3Cg%20fill%3D%22%23@%22%3E%3Cpath%20d%3D%22M1254%201163H51c-26%200-51-25-51-51V981c0-23%2022-51%2051-51h1075c22%200%2036-13%2044-30l96-192c4-9%201-12-8-12H51c-22%200-51-25-51-51V514c0-23%2023-51%2051-51h1298c27%200%2046-13%2056-33l200-401c9-18%2020-29%2041-29h182c19%200%2029%207%2018%2029l-554%201111c-5%2010-19%2023-38%2023z%22%2F%3E%3Ccircle%20cx%3D%22207%22%20cy%3D%221453%22%20r%3D%22181%22%2F%3E%3Ccircle%20cx%3D%221062%22%20cy%3D%221453%22%20r%3D%22181%22%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E'); > 

Используется данная примесь следующим образом (образец произвольный):

Вот, собственно, и все. LESS- (SASS, Stylus, etc.) файлик с такими примесями отлично заменяет спрайт.

Для оптимизации и кодирования SVG я использовал GULP, плагины gulp-svgo и gulp-data-uri-stream. Да, этот метод дает возможность менять лишь размеры иконки, цвет заливки и обводки, но в большинстве своем этого вполне достаточно.

Источник

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