In the previous examples, we've seen some boring rectangles with not very eye-catchy look. Now let's see how
we can improve that.
In JointJS, only SVG standard is the limit on what you can do with your elements. For styling elements, you
need to have a basic
understanding on how the element is structured in terms of its underlying SVG DOM subtree. For instance, our
joint.shapes.basic.Rect
element consists of this SVG structure (TIP: inspect your diagram with the Developer Tools of your favourite
browser):
<g class="element basic Rect">
<g class="rotatable">
<g class="scalable">
<rect />
</g>
<text />
</g>
</g>
Having known this, the first thing that might have popped on your mind is: Hey, I can style my elements in CSS.
The answer is yes, you're absolutely right!
It's perfectly fine to style your elements in CSS. Just keep in mind that you're styling SVG, not HTML. In that
case, if you're completely new to SVG,
you might want to take a look at e.g.:
Fills and Strokes tutorial on MDN.
If you use external CSS for styling your elements, all your elements will have the same style. Also note that,
by SVG specification,
CSS properties have higher precedence over SVG element attributes (which I find a bit counter-intuitive). That
means that
whatever you define in your external stylesheet cannot be overruled by setting element specific attributes with
the method below.
A better approach is using the attr method of joint.dia.Element
.
rect.attr({
rect: { fill: '#2C3E50', rx: 5, ry: 5, 'stroke-width': 2, stroke: 'black' },
text: {
text: 'my label', fill: '#3498DB',
'font-size': 18, 'font-weight': 'bold', 'font-variant': 'small-caps', 'text-transform': 'capitalize'
}
});
I left the styling of the other rectangles in this example out of this text. If you want to look at it
anyway,
inspect this page, find the tutorial.js
script and search the function
elementStyling()
.
As you can see, the element.attr()
method takes one object as its argument. The keys
of the object
is CSS selectors matching the SVG DOM elements that our element consists of. The selectors in this example
our
quite simple but you can imagine it might get more complicated for other elements or even your own, custom,
elements.
A more complicated selector might look like: '.section2 .port1 text'
.
The values of the object passed represent a flat object (with one exception and that is the style
attribute) with SVG/CSS attributes that
will be used to style that element.
For additional styling options using filters and gradients, please see the Filters and Gradients tutorial.