Styles: Fill, Stroke, Opacity, and Fill-Opacity

Learn how to apply fill, stroke, opacity, and fill-opacity styles to your D3 elements.

We'll cover the following

What is a style?

Believe it or not, that’s as difficult a question to answer as, “What’s an attribute?” I like to think that an element can be selected and arranged on a web page with select and attr. But once it’s there, changes to how it looks are a matter for style. We will cover a range of qualities that neatly fit into this definition in the following section (such as fill, opacity, and stroke-width), but there are also a range of unusual style declarations that many may not have come across. I certainly hadn’t before writing this.

The other important thing to mention about setting styles for elements is that there are different ways to accomplish the task. We’ll go through the process of describing different styles, as they can be applied to individual elements in isolation. But there is a more powerful way to manage styles across a range of elements via (CSS) in the <style> section of a web page or even via an external style sheet. We will examine these possibilities at the end of the section.

Full disclosure: I have not figured out how to work some of the styles for D3.js. I’m afraid that clip-path and mask have exceeded my skill-set, and I will have to leave them for another day. I found that there are several good examples that make use of these styles, but I have struggled to present them in a simple example.

fill

The fill style will fill the element being presented with a specified color.

By default, most elements will be filled with black (the majority of the examples used in this chapter make no fill declaration).

The following example shows the syntax for filling a simple circle with the color red:

Get hands-on with 1200+ tech skills courses.