liveBook · Manning

Style

As explained in D3.js in Action, Third Edition

A DOM style is presentation information that controls an element's visual characteristics such as color, size, borders, and opacity.

A DOM style is presentation information that controls an element’s visual characteristics, including color, size, borders, and opacity. Styles describe appearance, while attributes describe values such as classes, IDs, or SVG geometry, and properties describe current state. section 1.2.1

D3 sets or modifies styles with selection.style(property, value). The method writes inline styles directly onto selected elements, which is especially useful when data changes the presentation dynamically. section 2.6

Apply styles with these practical rules:

  • Use an external CSS stylesheet when maintainability is the priority. section 2.6
  • Use style() when presentation changes dynamically with data. section 2.6
  • For SVG properties such as fill and stroke, choose attr() or style() consistently so shape-making and visual presentation remain easy to manage. section 2.6
const svg = d3.select(".responsive-svg-container")
  .append("svg")
    .attr("viewBox", "0 0 1200 1600")
    .style("border", "1px solid black");

This example adds an SVG container and gives it a one-pixel black border with style(). Inspecting the DOM reveals the resulting inline style. section 2.6

How D3.js in Action, Third Edition covers it

How deep it goes
Defines styles, distinguishes them from attributes and properties, and demonstrates inline application with selection.style().
Examples
Demonstrates an SVG border and competing fill values supplied by an SVG attribute, external CSS, and an inline style.
What it assumes
Introduces the HTML and DOM context before applying styles to SVG containers and shapes.
What you can do after
Apply styles to selected HTML or SVG elements with D3’s selection.style() method.
How it connects
Connects styles with the DOM, CSS, SVG, attributes, properties, and D3 selections.

Also explained in

Compare how 7 books explain style →

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.