D3 Tips and Tricks v4

Wednesday, 12 December 2012

The CSS Portion of a D3 Graph

The CSS is as follows...
body { font: 12px Arial;}

path { 
    stroke: steelblue;
    stroke-width: 2;
    fill: none;

.axis path,
.axis line {
    fill: none;
    stroke: grey;
    stroke-width: 1;
    shape-rendering: crispEdges;
So Cascading Style Sheets give you control over the look / feel / presentation of the content. The idea is to define a set of properties to objects in the web page.

They are made up of 'Rules'. Each rule has a 'selector' and a 'declaration' and each 'declaration' has a property and a value (or a group of properties and values).

For instance in the example code for this web page we have the following rule;
body { font: 12px Arial;} 
'body' is the selector. This tells you that on the web page, this rule will apply to the 'body' of the page. This actually applies to all the portions of the web page that are contained in the 'body' portion of the HTML code (everything between <body> and </body> in the HTML bit).

{ font: 12px Arial;} is the selector portion of the rule. It only has the one declaration which is the bit that is in between the curly braces.

So font: 12px Arial; is the declaration. The property is 'font:' and the value is '12px Arial;'. This tells the web page that the font that appears in the body of the web page will be in 12 px Arial.
Sure enough if we look at the axes of the graph...
We see that the font might actually be 12 px Arial!

Let's try a test. I will change the Rule to the following;
body { font: 16px Arial;}
and the result is...
Ahh.... 16px of goodness!

And now we change it to...
body { font: 16px times;}
and we get...
Hmm... Times font.... I think we can safely say that this has had the desired effect.

So what else is there?

What about the bit that's like;
path { 
    stroke: steelblue;
    stroke-width: 2;
    fill: none;
Well, the whole thing is one rule, 'path' is the selector. In this case, 'path' is referring to a line in the D3 drawing nomenclature.

For that selector we have three declarations. They give values for the properties of 'stroke' (in this case colour), 'stroke-width' (the width of the line) and 'fill' (we can fill a path with a block of colour).

So let's change things :-)
path { 
    stroke: red;
    stroke-width: 5;
    fill: yes;

Wow! So the line is now red, it looks about 5 pixels wide and it's tried to fill the areas roughly defined by the curve with a black colour.

It ain't pretty, but it certainly did change. In fact if we go;
fill: blue;
We'll get...
So the 'fill' property looks pretty flexible. And so does CSS.

No comments:

Post a Comment