Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS class name in SVG style is global?

Tags:

css

svg

If I have several SVG elements in a HTML body, where each SVG references a CSS class name, and this class name is defined in one of the SVG elements like below, then all the SVG elements are affected by this style. I am trying to find out whether this is by design, and how to make sure that the CSS class name is local to the SVG that defines it.

<svg xmlns="http://www.w3.org/2000/svg" width=100 viewBox="0 0 15 10">
    <path class="iconMain" d="M7.5,9,1,4.78789l.46713-.91645L7.5,7.85543l6.03287-3.984L14,4.78789ZM14,1.91646,13.53287,1,7.5,4.98349,1.46713,1,1,1.91646l6.5,4.2121Z" />
</svg>
<svg xmlns="http://www.w3.org/2000/svg" width=100 viewBox="0 0 15 10">
    <defs>
        <style>
            .iconMain {
                fill: #9cbacf;
            }
        </style>
    </defs>
    <path class="iconMain"
        d="M7.5,9,1,4.78789l.46713-.91645L7.5,7.85543l6.03287-3.984L14,4.78789ZM14,1.91646,13.53287,1,7.5,4.98349,1.46713,1,1,1.91646l6.5,4.2121Z" />
</svg>

https://codepen.io/napsta32/pen/ExOPGae

like image 614
akonsu Avatar asked Dec 05 '25 23:12

akonsu


1 Answers

You are misunderstanding the usage of defs they are used to define graphical elements to be used later on with the tag use If you put something inside that is not a graphical element it will go straight into the document, a style or script for example. And even the defs are global, if you define one element inside an svg you can use it in another one.

<svg xmlns="http://www.w3.org/2000/svg" width=100 viewBox="0 0 15 10">
  <defs>
  <circle id="circle_defined_in_first_svg" cx="1" cy="2" r="6" />
 </defs>
  
    <path class="iconMain" d="M7.5,9,1,4.78789l.46713-.91645L7.5,7.85543l6.03287-3.984L14,4.78789ZM14,1.91646,13.53287,1,7.5,4.98349,1.46713,1,1,1.91646l6.5,4.2121Z" />
</svg>

<svg xmlns="http://www.w3.org/2000/svg" width=100 viewBox="0 0 15 10">
    <defs>
        <style>
            .iconMain {
                fill: #9cbacf;
                background-color:pink;
            }
        </style>       
      <script>
        var variableInsideDef = 7987;
      </script>      
    </defs>
    <path class="iconMain"
        d="M7.5,9,1,4.78789l.46713-.91645L7.5,7.85543l6.03287-3.984L14,4.78789ZM14,1.91646,13.53287,1,7.5,4.98349,1.46713,1,1,1.91646l6.5,4.2121Z" />
  
  <use x="5" y="5" href="#circle_defined_in_first_svg"/>
  
</svg>

<p class="iconMain"> P ELEMENT IN ROOT AFFECTED BY THE STYLE INSIDE DEF</p>

<script>
  alert("Variable declared inside def: " + variableInsideDef)
</script>

The only way I can think for you to have styles aplying only to a specific svg is to have a different class for each one...

like image 111
Paulo Fernando Avatar answered Dec 07 '25 17:12

Paulo Fernando



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!