Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS selector specifity with SVG inside <object>

I have the following code:

<body class="active">
    <object data="css/svg/circle.svg" type="image/svg+xml">
        <p> Your browser doesn't support SVG.</p>
    </object>
</body>

The SVG is simple like:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?xml-stylesheet href="../style.css" type="text/css"?>
<svg id="circle" height="100" width="100">
    <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg> 

The active class on <body> is toggled through javascript. Then I have the following CSS:

#circle {
    opacity: 1;
}
.active #circle {
    opacity: 0.5;
}

The thing is, if I add the SVG with the <object> tag, the second selector, active #circle, doesn't work. If I put the SVG inline then it works. Note that I am including the CSS on the SVG file as well. I would like to use the <object> because the real SVG isn't really so simple so my html would get messy. Is there a way to achieve that?

Thanks in advance,

like image 282
João Menighin Avatar asked May 17 '26 22:05

João Menighin


1 Answers

Here is a few ways you might could use

Leave object empty and load it as an inline svg using ajax, on page load, ...

HTML

<object data="" data-svg="path-2-image.svg" type="image/svg+xml">
    <p> Your browser doesn't support SVG.</p>
</object>

...or why not into a plain element, like a div

<div data-svg="path-2-image.svg">
</div>

Script (concept)

<script>
    // on load/dom ready
    var trg = document.querySelector('[data-svg]');
    var svgpath = trg.getAttribute('data-svg');
    call-your-SVGloader-function(obj,svg);
</script>

Note: I also think you need to use trg.innerHTML = ... for the object as you do with the div


Was also thinking of using an image, though haven't tried if this actually works

<img src="path-2-image.svg" alt="">
like image 87
Asons Avatar answered May 19 '26 10:05

Asons