skip to Main Content

I have the following code:

.container{
    
    width: 100px;
    height: 200px;
    
    background-color: red;
    
    resize: both;     /* Just to make it... */
    overflow: hidden; /* ...resizable for testing. */
    
}
<div class="container">
    <svg width="100%" height="100%">
        <circle cx="50%" cy="50%" r="25%" fill="black"></circle>
    </svg>
</div>

As I resize .container, I can easily see that:

  • cx is percentage of the width
  • cy is percentage of the height

But I cannot understand what r is percentage of. What is r percentage of?

2

Answers


  1. cx (Center X):

    This attribute defines the x-coordinate of the center of the circle.
    In your code, cx="50%" means that the center of the circle is positioned at 50% of the width of the SVG container. This centers the circle horizontally within the SVG.

    cy (Center Y):

    This attribute defines the y-coordinate of the center of the circle.
    cy="50%" means that the center of the circle is positioned at 50% of the height of the SVG container. This centers the circle vertically within the SVG.

    r (Radius):

    This attribute defines the radius of the circle.
    r="25%" means that the radius of the circle is 25% of the smallest dimension (width or height) of the SVG container. This determines the size of the circle relative to the SVG container.

    Read the documentation

    Login or Signup to reply.
  2. As commented by Roko C. Buljan when using % units the relative value refers to the normalized diagonal.

    See the W3C SVG specs "8.9. Units"

    For any other length value expressed as a percentage of the SVG
    viewport, the percentage must be calculated as a percentage of the
    normalized diagonal of the ‘viewBox’ applied to that viewport. If no
    ‘viewBox’ is specified, then the normalized diagonal of the SVG
    viewport must be used. The normalized diagonal length must be
    calculated with sqrt((width)**2 + (height)**2)/sqrt(2).

    here’s an example

    let w = 100;
    let h = 200;
    let c = Math.sqrt(w ** 2 + h ** 2) / Math.sqrt(2)
    let rAbsolute = c * 0.25
    
    // get absolute radius via baseVal
    let r = c1.r.baseVal.value
    console.log(rAbsolute, r)
    .container {
      width: 100px;
      height: 200px;
      background-color: red;
    }
    <div class="container">
      <svg width="100%" height="200px">
            <circle id="c1" cx="50%" cy="50%" r="25%" fill="#ccc"></circle>
            <circle cx="50%" cy="50%" r="39.52847075210474" fill="none" stroke="blue" />
        </svg>
    </div>

    You can also check your calculations using the baseVal property from the SVGAnimatedLength interface.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search