SVG

How to insert a CSS style into an SVG with JavaScript?

If you need that, you could try something like the following instead: Update : IE work-around as per Daniel’s comment: (The problem seems to be that IE does not support the .innerHTML for SVG elements.) Use the of a and set it to and then append all nodes in the ‘s to the element via: where is the element. Solution 1: OPTION 1 — Using generic css styles Personally I create several fill colours and simply apply the class to the svg where required. HTML CSS OPTION 2 — SVG’s targeted by unique class If your svg has several paths you can target each using other classes.

How to insert a CSS style into an SVG with JavaScript?

I try to add a CSS style sheet to an SVG. So what I have is the following svg:

And I would like to add a style sheet to this like:

var defs = document.getElementById('mydefs'); var style = document.createElementNS("http://www.w3.org/2000/svg", 'style'); style.type = 'text/css'; style.insertRule('.myclass < fill: red; >', style.cssRules.length); defs.appendChild(style); 

But the insertRule (and cssRules ) seems not to be supported. Here is the (not working) codepen:

var defs = document.getElementById('mydefs'); var style = document.createElementNS("http://www.w3.org/2000/svg", 'style'); defs.appendChild(style); style.type = 'text/css'; style.sheet.insertRule('.myclass < fill: red; >', style.sheet.cssRules.length); 

(BTW, you can also just use the parent document’s style sheet:)

var style = document.createElement('style'); document.head.appendChild(style); style.type = 'text/css'; style.sheet.insertRule('.myclass < fill: red; >'); 

The above approaches don’t show any CSS in the inspector. If you need that, you could try something like the following instead:

var defs = document.getElementById('mydefs'); var style = document.createElementNS("http://www.w3.org/2000/svg", 'style'); defs.appendChild(style); style.innerHTML = '.myclass < fill: red; >'; 

Update : IE work-around as per Daniel’s comment:

Читайте также:  Вывод формулы в javascript

(The problem seems to be that IE does not support the .innerHTML for SVG elements.)

Use the .innerHTML of a and set it to .myclass and then append all nodes in the div ‘s .childNodes[0].childNodes[0] to the style element via:

Array.prototype.slice.call(div.childNodes[0].childNodes[0].childNodes).forEach(function(el) < element.appendChild(el); >); 

Css class styles aren’t applied to svg, You can add the class declaration in your .svg file, directly inserting a

Using an SVG and Apply CSS from Stylesheet

So I’ve browsed several articles and questions here, but no holy grail.

I have an external file icon.svg , and I want to use it in several HTML files and have a different fill and sizes for each use.

I can’t use from what I gather since it doesn’t allow for styles from CSS sheets unless you reference that sheet from the SVG file itself, which kind of defeats the entire purpose.

The only way I found how to do this is like this:

And the CSS applies. But I can only seem to do it if I add symbol nodes in the SVG file and give them an ID, which I’d rather not do.

Also, could it be that this might be not supported in all major browsers ?

Added tags for javascript/angularjs since the solution was JS based. (see answer)

OPTION 1 — Using generic css styles

Personally I create several fill colours and simply apply the class to the svg where required.

OPTION 2 — SVG’s targeted by unique class

If your svg has several paths you can target each using other classes.

.icon < fill:#000; height:20px; width:20px; >.symbol < height:40px; width:40px; >.symbol .path1 < fill:#b00; >.symbol .path2

OPTION 3 — SVG’s as background images

DEMO

To utilise svg’s like images they can be targeted with css and even used as background images in css but each svg symbol would need to be a unique file.

To use the svg as different height and widths simply edit in css using additional classes to overwrite defaults using specificity:

OPTION 4 — Inline Svgs (My recommendation)

DEMO

Place the svg file directly in your html to reduce http requests and improve control.

Place just after your body tag at the top of your html

Then you can call the svg’s from anywhere using the svg’s id.

I ended up using and manipulating it after the SVG was rendered, in a way that would help me change the styling.

To anyone interested in the more technical details, I’ve written the process here in my blog.

I’ve created a directive in Angular to handle it, but of course you don’t have to use Angular and could take the relevant parts and use it however you want.

Edit: Wrote a bower for it, you can get it here.

How to apply a style to an embedded SVG?, Yet another option is to use the first method, to insert a style element, and then add an @import rule, e.g styleElement.textContent = «@import url(my-style.css)

Add CSS styling to SVG

I have an SVG in which i want to add a particular styling to all circle having r=»5″

I have tried this but does not work

var allElements = document.getElementsByClassName("bubble-plot-chart-circle"); for(var i = 0; i < allElements.length; i++) < var element = allElements[i]; if(element.getAttribute("r") === "5") < // it takes the initial inline style which was applied at the time of crating the SVG element.setAttribute("opacity", "0 !important");// does not work for SVG element.addClass("test"); // does not work for SVG >> 

can any one help me on this as i am new to SVG

I used querySelectorAll to get the filtered elements with provided class name and attribute.

var allElements = document.querySelectorAll(".bubble-plot-chart-circle[r='5']"); // filtering as required for(var i = 0; i < allElements.length; i++) < var element = allElements[i]; element.setAttribute("opacity", "0"); // !important is invalid in presentation attribute (check comment above) element.classList.add("test"); // JavaScript's method instead of jquery's addClass method >

and also addClass method is not available for JavaScript DOM object. It is available for jQuery object. If you want to use addClass method, convert the DOM object to jquery object as shown below:

var jqueryElement = $(element); jqueryElement.addClass('test'); 

And also, you can do the same selection using CSS as well:

Its working. See this. Use element.classList.add() instead:

Actually your code does work. What doesn’t work, is your attribute.

I think you should look at https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-opacity

  var allElements = document.getElementsByClassName("bubble-plot-chart-circle"); for(var i = 0; i 

You can filter elements by attribute as you do. However, you need to wait till content is loaded.

A short D3 solution (since you have the d3js tag in your question), using selection and filter :

var circles = d3.selectAll("circle").filter(function()< return d3.select(this).attr("r") == 5;>); 

And that’s all you need: circles is a selection containing all the circles with a 5-pixel radius.

Once we have the proper selection, we can manipulate it the way we want. For instance, making all these circles moving to the right:

circles.transition().duration(1000).attr("transform", "translate(100,0)"); 
var circles = d3.selectAll("circle").filter(function()< return d3.select(this).attr("r") == 5;>); circles.transition().delay(500).duration(1000).attr("transform", "translate(100,0)");

Svg in css class Code Example, Queries related to “svg in css class” · svg in html · how to use svg in html · css svg · html svg image · svg tag html · import svg html · how to add svg to html · html

Источник

Style SVG with CSS

You can’t change x/y position of g element but you can use transform=»translate(x,y)»: info on SVG G: http://tutorials.jenkov.com/svg/g-element.html Solution: When an SVG is used in an image context, be that via or in this case via a CSS background-image it must be complete in a single document. SVG document: HTML document: These two documents need to run from a server, so not directly from the filesystem.

Style SVG with CSS

Correct (but possibly slow) solution

This is a bug of the Chartist library. They are calculating their label position so it is not center-aligned to the category.

For the permanent solution, you need to take it up with them, so the bug is fixed on their side.

You can find author’s contact details on this GitHub page.

Temporary solution

In the interim, you can apply a dirty fix by shifting the whole labels block to the right.

As IE11 ignores transform properties applied via CSS, we will need to apply it directly to the SVG node properties.

Since you have jQuery on your page, we’ll use that for the simplicity sake:

Needless to say, this needs to go after your other chart code.

How about modifying x attribute via Javascript?

   

Text tag is child of svg g element. You can’t change x/y position of g element but you can use transform=»translate(x,y)»:

info on SVG G: http://tutorials.jenkov.com/svg/g-element.html

Using Javascript in CSS, IE and Firefox both contain ways to execute JavaScript from CSS. As Paolo mentions, one way in IE is the expression technique, but there’s also the more obscure HTC behavior, in which a seperate XML that contains your script is loaded via CSS. A similar technique for Firefox exists, using XBL. These …

Embedding SVG in CSS via use reference

When an SVG is used in an image context, be that via or in this case via a CSS background-image it must be complete in a single document. References outside the document are not allowed.

So #arrow must point to an element with the id arrow in that base64 encoded SVG document.

SVG Tutorial, SVG defines vector-based graphics in XML format. Examples in Each Chapter With our «Try it Yourself» editor, you can edit the SVG, and click on a button to view the result. SVG Example

My first SVG

Manipulate SVG viewbox with JavaScript (no libraries)

It would be good to see the context of the svg, but the following worked for me with a pure SVG document:

shape = document.getElementsByTagName("svg")[0]; shape.setAttribute("viewBox", "-250 -250 500 750"); 

Maybe it’s because viewBox is case-sensitive?

You have an error in your code: «viewbox» is different than «viewBox». B is in uppercase. Change the code to:

a.setAttribute("viewBox","0 0 " + SVGWidth + " 300"); 

I had a very similar use case, where resizing SVG was crucial for responsive design.

const windowWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; const windowHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; // used getElementById for specific SVG const shape = document.getElementById("background-svg"); function onWindowResize() < console.log(windowWidth, windowHeight); if (windowWidth < 600 || windowHeight < 900) < shape.setAttribute("viewBox", "0 0 400 800"); >// Added an Event Listener window.addEventListener("resize", onWindowResize); 

This method worked well enough for me, I hope there’s room for improvement, would be glad to find alternative solutions. Happy coding!

SVG Tutorial – How to Code Images with 7 Examples, The SVG tag. First, we have to talk about the svg tag itself. This tag contains the image elements and defines the frame of our image. It sets the inner size and the outer size of the image. The width and height property define how much space the image takes up in the browser. There’s often a viewBox property …

Loading javascript libraries included in an appended SVG file

If you can make this work with any JavaScript library embedded in SVG is a good question, but here I have an example where I use chroma.js like you suggested.

A reference to the SVG document is added to the data attribute of . Here it is static, but I guess it could be dynamically updated. Now the SVG is doing its thing, like setting a color on the and animating the cy attribute of the . At any point I can grab the contentDocument (contentDocument.documentElement.outerHTML) of , that is the SVG document at a particular point. If values in the document is changing this will affect the contentDocument. Now I can take the string (outerHTML) and turn that into a data URI. The data URI can be set as src on an image object and the image can be rendered in the element. In the outerHTML you can see that there are also references to the JavaScript library and the JavaScript code that I wrote, but this is not executed in the image when rendered into .

         

These two documents need to run from a server, so not directly from the filesystem.

From what I have tested the SVG animations and CSS animations are not working in this setup. Only the «animations» in JavaScript where you manipulate the DOM is working.

W3.CSS Home, W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

Источник

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