This example demonstrates the basic use case of cx
, and how the CSS cx
property takes precedence over the cx
attribute.
HTML
We include two identical <circle>
and two identical <ellipse>
elements in an SVG; their cx
attribute values are 50
and 150
, respectively.
<svg xmlns="http://www.w3.org/2000/svg">
<circle cx="50" cy="50" r="30" />
<circle cx="50" cy="50" r="30" />
<ellipse cx="150" cy="50" rx="20" ry="40" />
<ellipse cx="150" cy="50" rx="20" ry="40" />
</svg>
CSS
With CSS, we style only the first circle and first ellipse, allowing their twin shapes to use default styles (with (fill
defaulting to black). We use the cx
property to override the value of the SVG cx
attribute and also give it a fill
and stroke
to differentiate the first shapes in each pair from their twin. The browser renders SVG images as 300px
wide and 150px
tall by default.
svg {
border: 1px solid;
}
circle:first-of-type {
cx: 30px;
fill: lightgreen;
stroke: black;
}
ellipse:first-of-type {
cx: 180px;
fill: pink;
stroke: black;
}
Results
The style circle's center is 30px
from the left edge of the SVG viewport and the styled ellipse is 180px
from that edge, as defined in the CSS cx
property values. The unstyled shapes centers are 50px
and 150px
from the left edge of the SVG viewport, as defined in their SVG cx
attribute values.