what's meaning of the percentage for color sto

2019-08-05 16:20发布

This maybe a simple question, but I didn't find a clear explanation for this.

I know in css3, the syntax for setting up a radial gradient is as following:

radial-gradient(shape size at position, start-color, ..., last-color);

If I set sth like this:

radial-gradient(circle at 50% 50%, #f00 50%, transparent 50%);

I thought the red circle will be positioned in the center, and the radius of the red circle would be 50%*containerWidth(or containerHeight). i.e. the circle will just touch the edge of the outer container, but what I got is not, please see the demo:

DEMO ON JSFIDDLE

So can anybody help to explain what's the exact meaning of the 50% here please(#f00 50%)? Many thanks.


based on @'s answer:

the 50% is refered to the diagonal from the center to the square corner

I also put several demo here:

MORE DEMO ON JSFIDDLE

Because under the default option, the percentage is between the gradient stop radius and the diagonal, so when the ratio is 2**0.5/2≈0.707, the circle will touch the edges of the square.

2条回答
我只想做你的唯一
2楼-- · 2019-08-05 17:02

The 50% in the color stop depends on the size of the image that is being generated.

And the size of the image depends on your choice between the 4 posible values for this property.

If you do not set it, the farthest-corner option is choosen (so, in your example, the 50% is refered to the diagonal from the center to the square corner

div{
  width:100px;
  height:160px;
  border:solid 1px blue;
  display: inline-block;
}

.gradient1{
  background-image: radial-gradient(circle closest-side at 50% 40%, #f00 50%, transparent 50%);
}
.gradient2{
  background-image: radial-gradient(circle closest-corner at 50% 40%, #f00 50%, transparent 50%);
}
.gradient3{
  background-image: radial-gradient(circle farthest-side at 50% 40%, #f00 50%, transparent 50%);
}
.gradient4{
  background-image: radial-gradient(circle farthest-corner at 50% 40%, #f00 50%, transparent 50%);
}
<div class="gradient1"></div>
<div class="gradient2"></div>
<div class="gradient3"></div>
<div class="gradient4"></div>

查看更多
闹够了就滚
3楼-- · 2019-08-05 17:04

center 50% 50% places the gradient center at the center of the container, #f00 50% colors the gradient with red color up to 50% of radius the rest 50% being transparent, exactly what you see in jsfiddle. In other words the percent refers to the size (i.e radius) of the gradient object (which in the case of a radial gradient it is the radius, as it unfolds from the center outwards).

enter image description here

https://developer.mozilla.org/en-US/docs/Web/CSS/radial-gradient

查看更多
登录 后发表回答