selection.style() sets or modifies a CSS style property on every element in a D3 selection. Pass the property name and value, then chain the method into a selection-building expression. For example, applying style("border", "1px solid black") to an SVG container makes its working area visible. section 2.6
Use selection.style() when presentation needs to be applied directly through D3, especially when values change with data:
- Apply inline CSS to selected DOM or SVG elements with a property name and value. section 2.6
- Inspect the DOM to see the resulting declaration inside the element’s style attribute. section 2.6
- Choose between style(), attr(), and external CSS for SVG presentation; fill and stroke can be expressed through either style or attributes. section 2.6 section 2.7
Styling an SVG rectangle
Create a rectangle with an attribute-based fill, then override that presentation with an inline style: svg.append("rect").attr("x", 10).attr("y", 10).attr("width", 414).attr("height", 16).attr("fill", "turquoise").style("fill", "plum"); The rectangle displays the inline plum fill, illustrating how style() participates in the cascade. section 2.6 section 2.7
const svg = d3.select(".responsive-svg-container")
.append("svg")
.attr("viewBox", "0 0 1200 1600")
.style("border", "1px solid black");
View a complete chained selection that appends an SVG and applies a one-pixel black border with style(). section 2.6
svg
.append("rect")
.attr("x", 10)
.attr("y", 10)
.attr("width", 414)
.attr("height", 16)
.attr("fill", "turquoise")
.style("fill", "plum");
View the rectangle example combining SVG attributes with an inline fill set by style(). section 2.6
