This example demonstrates the basic use case of stop-opacity
, and how the CSS stop-opacity
property takes precedence over the stop-opacity
attribute.
HTML
We have an SVG with a few <polygon>
stars and three <linearGradient>
elements: each has three <stop>
elements defining three color-stops that create a gradient going from blue to white to pink; the only difference between them is the id
value.
<svg viewBox="0 0 250 120" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="myGradient1">
<stop offset="5%" stop-color="#66ccff" stop-opacity="1" />
<stop offset="50%" stop-color="#fefefe" stop-opacity="1" />
<stop offset="95%" stop-color="#f4aab9" stop-opacity="1" />
</linearGradient>
<linearGradient id="myGradient2">
<stop offset="5%" stop-color="#66ccff" stop-opacity="1" />
<stop offset="50%" stop-color="#fefefe" stop-opacity="1" />
<stop offset="95%" stop-color="#f4aab9" stop-opacity="1" />
</linearGradient>
<linearGradient id="myGradient3">
<stop offset="5%" stop-color="#66ccff" stop-opacity="1" />
<stop offset="50%" stop-color="#fefefe" stop-opacity="1" />
<stop offset="95%" stop-color="#f4aab9" stop-opacity="1" />
</linearGradient>
</defs>
<polygon points="40,10 10,100 80,40 0,40 70,100" />
<polygon points="125,10 95,100 165,40 85,40 155,100" />
<polygon points="210,10 180,100 250,40 170,40 240,100" />
</svg>
CSS
We include a stroke
and stroke-width
making the polygon path line visible.
Each polygon
has a gradient background set using the fill
property; the gradient's id
is the url()
parameter. We set magenta
as the fallback color.
We define the opacity of the stops of each gradient using the stop-opacity
property.
The SVG has a striped background to make the transparency settings more apparent.
polygon {
stroke: #333;
stroke-width: 1px;
}
polygon:nth-of-type(1) {
fill: url("#myGradient1") magenta;
}
polygon:nth-of-type(2) {
fill: url("#myGradient2") magenta;
}
polygon:nth-of-type(3) {
fill: url("#myGradient3") magenta;
}
#myGradient1 stop {
stop-opacity: 1;
}
#myGradient2 stop {
stop-opacity: 0.8;
}
#myGradient3 stop {
stop-opacity: 25%;
}
Results
The first star is fully opaque. The fill of the second star is 80% opaque because the color stops are slightly translucent; the stop-opacity: 0.8;
overrode the stop-opacity="1"
element attribute value. The fill of the last star is barely noticeable with color stops that are 25% opaque. Note the stroke is the same opaque dark grey in all cases.
Note: Because we used the same stop-opacity
value for all the sibling <stop>
elements in the linear gradient, we could have instead used a single <linearGradient>
with fully opaque stops, and set a value for each <polygon>
s fill-opacity
property instead.