Home > Blockchain >  style SVG within a page with css
style SVG within a page with css

Time:04-02

I have an svg in a file that represents a workflow - ie a bunch of boxes with lines between them - so say I have four rectangles.

In the app I have a mode - and I want appropriate rectangle to highlight based on the mode. So I want to do a css like:

#workflow rect {background-color:white}
.mode_1 #workflow rect:nth-child(1) {fill:red}
.mode_2 #workflow rect:nth-child(2) {fill:orange}
.mode_3 #workflow rect:nth-child(2) {fill:yellow}

// etc

And it works fine if I have inline svg. However, the workflow diagram is moderately complicated and long. I need to be able to store and edit it in a separate file so I can use an svg editor etc - and I can't find any way of styling it from the parent page. I've tried:

<img src="workflow.svg"/>

the browser doesn't see it as pieces at all

<object data="workflow.svg"/>

it's like an iframe, and it doesn't respond to the page's css

<svg>
    <use xlink:href="workflow.svg#diagram">
</svg>

the svg appears as some sort of "shadow object" - and still doesn't respond to css. I'm on the same domain - so cross site issues shouldn't be a problem.

I can get the effect I want by using javascript, or using multiple svg files - but is there any way to do it with just css and svg?

CodePudding user response:

You'll have use different svg images. As far as I can tell, you can't use css to adjust it. You would have to edit the file itself.

CodePudding user response:

not really what I was looking for, but I thought of a javascript hack to get me there... its ugly but it works - here's a simple example:

<body>   
    <svg_embed href="workflow.svg"/>
</body>

<script>
    $("svg_embed").each( (index, element) => 
         fetch( $(element).attr( "href" ) )
           .then( response => response.text())
           .then( xml => { $(element).html( xml )}))
</script>

so this reads and embeds the svg - thus making it fully css-able.

  • Related