Global CSS class name in SVG?

,

I am trying to understand how to scope a CSS class name to a single SVG element when multiple SVG elements are present in a HTML body. The code example below shows two SVG elements that both reference a CSS class name, iconMain, which is defined in one of the SVG elements.

<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>

Example CodePen

To scope a CSS class name to a single SVG element when multiple SVG elements are present in an HTML body, you can use the id attribute instead of the class attribute. Here’s the updated code:

<svg xmlns="http://www.w3.org/2000/svg" width="100" viewBox="0 0 15 10">
    <path id="iconMain1" 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>
            #iconMain2 {
                fill: #9cbacf;
            }
        </style>
    </defs>
    <path id="iconMain2" 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>

In this updated code, I’ve assigned a unique id to each SVG element instead of using the same class name. Then, in the CSS, I’ve used the id selector (#iconMain1 and #iconMain2) to target each SVG element separately and apply the desired styles.