Why CSS and SVG radial gradients do not match?
Asked Answered
D

2

7

The outcome of the gradients should not be the same? Why are they so different... Am I missing something?

DEMOSTRATION

SVG

<radialGradient cx="50%" cy="50%" r="100%" spreadMethod="pad" id="radGrad">
  <stop offset="0" stop-color="#fff"/>
  <stop offset="0.5" stop-color="#00f"/>
</radialGradient>

CSS

background: radial-gradient(ellipse at center, #fff 0%,#00f 50%);
Denice answered 7/4, 2014 at 14:45 Comment(2)
interestingly, the browsers I tested (Ch,FF,O,IE) pretty much agree on the differences, so it might be a slight difference in the spec I guess.Wirer
The relevant specs to look at are w3.org/TR/SVG11/pservers.html#RadialGradients and w3.org/TR/css3-images/#radial-gradientsBrewing
T
6

The CSS gradient runs from the center to the side. The SVG gradient runs from the center to the corner. So the SVG gradient radius is 1.414 (√2) times larger than the the CSS gradient radius.

I haven't found a way to make the SVG gradient be sized from the side instead of the corner. So to match the CSS gradient stop at 50%, I calculated the SVG gradient stop manually:

(CSS gradient radius / SVG gradient radius / 2) or (1 / 1.414 / 2).

That means: <stop offset="0.3536" stop-color="#00f"/>

http://codepen.io/anon/pen/emLqy/


… In Google Chrome, there's still a small difference (presumably no dithering) in how the gradients are rendered. In Firefox and Safari both gradients look smooth.

Torr answered 7/4, 2014 at 16:6 Comment(4)
This is more of an issue of whether the gradient is sized with respect to sides or to corners, which is why you're finding yourself using the Pythagorean theorem to determine how to adjust the color stops.Brewing
I almost accepted this answer (it does solve half of the issue) but the real problem remains... the css is way smoother here ...Denice
It's a problem with Chrome (presumably no dithering). Unfortunately, there's nothing you can do about that. I edited my answer accordingly.Torr
dithering ... that's the magic word! you got me Sebastian! ;DDenice
M
0

When you define your radial gradient radius as "100%', this means 100% in objectBoundingBox units: which are %'s of the square root of the sum of the squares of the height and width of your bounding box. Gradient stops are defined relative to this size.

Mcclurg answered 7/4, 2014 at 20:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.