liveBook · Manning

Style attribute

As explained in D3.js in Action, Third Edition

An HTML or SVG attribute whose value contains CSS declarations applied directly to that element.

The style attribute contains CSS declarations applied directly to one HTML or SVG element. Inline styles can control properties such as borders, fills, fonts, and colors. section 1.2.4

Use the style attribute with these practical rules:

  • Apply it to each element that needs the same styling, or style a wrapping SVG group; external stylesheets and shared classes are more efficient for broad reuse. section 1.2.4
  • Set or modify it in D3 with selection.style(property, value), which injects an inline style into the selected DOM element. section 2.6 section 2.7
  • Remember that inline styles override most declarations from external stylesheets and presentation attributes. section 2.6 section 2.7
  • Use inline styles cautiously for generic page layout because they can override styles users provide for reading comfort. section 10.2.5

Style an SVG container and shape with D3

const svg = d3.select(".responsive-svg-container") .append("svg") .attr("viewBox", "0 0 1200 1600") .style("border", "1px solid black"); svg.append("rect") .attr("x", 10) .attr("y", 10) .attr("width", 414) .attr("height", 16) .attr("fill", "turquoise") .style("fill", "plum"); The border becomes visible around the SVG, while the inline fill overrides the rectangle's turquoise presentation attribute. section 2.6

<div style="padding:10px; background:#00ced1;"> ... </div>
<text style="font-size:16px; font-family:serif;"> ... </text>

Compare inline styling on a traditional HTML element and an SVG text element. section 1.2.4

How D3.js in Action, Third Edition covers it

How deep it goes
Explains scope, precedence, D3 syntax, and SVG trade-offs, but stops short of detailed CSS cascade mechanics.
Examples
Uses HTML and SVG listings, an SVG border, and competing rectangle fill declarations from attributes, stylesheets, and inline styles.
What it assumes
Assumes basic HTML, SVG, CSS properties, DOM selections, and D3 chaining while teaching inline styling through a bar-chart exercise.
What you can do after
Apply it via D3's style() method to set visible properties and reason about conflicts with external CSS and presentation attributes.
How it connects
Connects CSS, external stylesheets, CSS selectors, SVG presentation attributes, D3 selections, and accessibility.

Also explained in

Compare how 7 books explain style attribute →

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.