Answer the question
In order to leave comments, you need to log in
How to style a group in SVG from external CSS?
Hello, I have such an SVG file that should show different strengths of the received signal.
<svg id="cell-strength" viewBox="0 0 29 18" xmlns="http://www.w3.org/2000/svg">
<style>
rect { fill: #545454; }
</style>
<rect rx="1" id="bar_1" height="7.2" width="5" y="10.8" x="0"/>
<rect rx="1" id="bar_2" height="10.8" width="5" y="7.2" x="8"/>
<rect rx="1" id="bar_3" height="14.4" width="5" y="3.6" x="16"/>
<rect rx="1" id="bar_4" height="18" width="5" y="0" x="24"/>
</svg>
<object class="cell-svg" type="image/svg+xml" data="cell.svg"></object>
<object class="cell-svg cell-svg--stength-2" type="image/svg+xml" data="cell.svg"></object>
<svg id="cell-strength" viewBox="0 0 29 18" xmlns="http://www.w3.org/2000/svg">
<style>
rect { fill: #545454; }
</style>
<g id="str-4">
<g id="str-3">
<g id="str-2">
<g id="str-1">
<rect rx="1" id="bar_1" height="7.2" width="5" y="10.8" x="0"/>
</g>
<rect rx="1" id="bar_2" height="10.8" width="5" y="7.2" x="8"/>
</g>
<rect rx="1" id="bar_3" height="14.4" width="5" y="3.6" x="16"/>
</g>
<rect rx="1" id="bar_4" height="18" width="5" y="0" x="24"/>
</g>
</svg>
.cell-svg--stength-2 g#str-2 rect {
fill: #fff;
}
Answer the question
In order to leave comments, you need to log in
It is better to insert svg into html, assign classes or id to the necessary elements and style them as normal elements
In general, you can get to the object tag only after loading, that is
object.addEventListener("load", function (){ здесь обработчик })
<object data="file.svg" type="image/svg+xml" id="for_svg" width="400px" height="300px"></object>
<script>
document.querySelector("#for_svg").addEventListener("load", function (){
let html = document.querySelector("#for_svg").contentDocument;
let rects = html.querySelectorAll("rect");
rects[0].style.fill = "#222";
rects[1].style.fill = "#fff";
rects[2].style.fill = "#fff";
rects[3].style.fill = "#999";
rects[4].style.fill = "#999";
})
</script>
<svg viewBox="0 0 460 300" xmlns="http://www.w3.org/2000/svg" width="460" height="300">
<rect width="460px" height="300px" x="0" y="0" />
<g>
<rect width="100px" height="80px" x="0" y="220" />
<rect width="100px" height="120px" x="120" y="180" />
<rect width="100px" height="200px" x="240" y="100" />
<rect width="100px" height="300px" x="360" y="0" />
</g>
</svg>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question