Home > Mobile >  How to override inherited svg style
How to override inherited svg style

Time:09-18

I am making a visualization program with d3 javascript.

There is a big group of lines. all the lines should start with opacity of 0.1. In this big group, there are some small groups. When an event is triggered, one of small groups visible and all other small groups invisible. Which small group is visible is dependent on the trigger event. I want to make one of small groups visible and all other small groups invisible by setting the opacity attribute.

So is there any keyword to make the group override the attribute or the style from its parent? Or is there any other similar attribute or style which can be overridden? Otherwise I may have to use for loop to traverse and modify every small groups, which is not very efficient.

<svg width="1000" height="500">
<g class="big_group" style="opacity: 0;">
    <g class='small_group inherit_opacity'>
        <line x1="100" y1="100" x2="200" y2="200" style="stroke: black;"></line>
    </g>
    <g class='small_group inherit_opacity'>
        <line x1="200" y1="100" x2="200" y2="200" style="stroke: black;"></line>
    </g>
    
    <g class='small_group' id='try_to_override_opacity_but_fail' style="opacity: 1;">
        <line x1="300" y1="200" x2="200" y2="200" style="stroke: black;"></line>
    </g>
</g>
</svg>

I intuitively thought there might be some kind of "override" keyword in "try_to_override_opacity_but_fail" to override the opacity in parent group.

CodePudding user response:

Only if you define the initial opacity with CSS, not with a style attribute:

<svg viewBox="0 0 1000 500">
  <style>
    g{
      opacity:0;
      stroke:black;
      stroke-width:10;
    }
  </style>
  <g>
    <line x1="100" y1="100" x2="200" y2="200"></line>
  </g>
  <g>
    <line x1="200" y1="100" x2="200" y2="200"></line>
  </g>
  <g style="opacity:1;">
    <line x1="300" y1="200" x2="200" y2="200"></line>
  </g>
</svg>

CodePudding user response:

the .svg files works fine with css so you can style them like:

svg {
    width: 200px;
    & > g {
        path:nth-last-of-type(2) {
            opacity: 0;
        }
    }
}

if you need to made changes dynamically, should read about style the elements by javascript ;)

  • Related