liveBook · Manning

Selection.style()

As explained in D3.js in Action, Third Edition

A D3 selection method that gets or sets CSS style properties on elements in a selection.

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

How D3.js in Action, Third Edition covers it

How deep it goes
Defines the two-argument setter, demonstrates inline output, and compares style() with attr() and external CSS.
Examples
Uses an SVG border and a rectangle whose inline plum fill overrides a turquoise fill attribute.
What it assumes
Assumes basic D3 selections and SVG construction while using CSS properties and selectors as the styling model.
What you can do after
Apply dynamic inline styles to D3 selections and inspect the resulting style attribute.
How it connects
Connects D3 selections with append(), attr(), CSS selectors, SVG presentation attributes, and external stylesheets.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of D3.js in Action, Third Edition. The section links point to the parts of the book it draws on.