dollaza
dollaza

Reputation: 213

How to style an svg using CSS without manipulating other svgs?

Originally I had one bar chart created using SVG:

 bars.append("rect")
   .attr("x", midX)
   .attr("y", 0)
   .attr("width", function(d) { return x(d.values[0].value); })
   .attr("height", y.bandwidth())
   .classed("highlight", function(d) { return d.key == '15-0000'; })

This is paired with the following css:

rect {
   fill: #ddd;
   stroke: #000;
   stroke-width: .5px;
}

.bar rect.highlight {
   fill: #F0B27A;
   stroke: #000;
   stroke-width: .5px;
}

I added a completely different bar chart:

svg.selectAll("rect")
    .data(barchartArray)
    .enter().append("rect")
    .attr("x", -300)
    .attr("y", function(d,i) { return i*11+70})
    .attr("width", function(d,i) { return d/1000; })
    .attr("height", 10);

How can I make changes to this rect in CSS without also manipulating the first bar chart? For example, how can I turn this chart to red without turning the first chart. I know that a class/id must be used but I'm not entirely sure how to format it in CSS.

Upvotes: 0

Views: 71

Answers (1)

k2snowman69
k2snowman69

Reputation: 1929

SVG's support classNames similar to normal HTML elements. Just add a className to the root svg element

svg.attr("class", "chart1")

Then change your css to include that class name as a parent.

.chart1 { rect { ... } }

svg {
   height: 50px;
   width: 50px;
}

svg.bigger {
   height: 100px;
   width: 100px;
}
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
  <circle cx="100" cy="100" r="100"/>
</svg>
<svg class="bigger" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
  <circle cx="100" cy="100" r="100"/>
</svg>

Upvotes: 1

Related Questions