Search code examples
htmlcssscss-mixinsscss-lint

How to create inner border into pie chart using HTML and CSS


I have created pie chart like this using HTML and css

enter image description here

I tried Below Code -

HTML -

<div class="pie-chart"></div>

CSS -

.pie-chart {
        margin-left: 10px;
        --size: 8rem;
        --fg: #369;
        --bg: #def;
        width: var(--size);
        height: var(--size);
        border-radius: 50%;
        display: grid;
        place-items: center;
        background:
          radial-gradient(closest-side, white 40%, transparent 0 99.9%, white 0),
          conic-gradient(
            #301B84 0 45%,
            #715fa5 45% 65%,
            #aca6cd 65% 75%,
            #d6d0e4 75% 100%);
        color: var(--fg);
      }

Expecting It should look like below pie chart (inner white border want to create it)-

enter image description here

Note - jQuery, Javascript is not allow for this (only html and css is allowed)

can someone help me with this.?


Solution

  • Conic gradients work in angled slices. If you were to add white gaps in the gradient between each section it would be thinner in the center and wider at the edge. That's likely not what you're looking for.

    So, there are two potential solutions.

    Solution 1: Use SVG. It was made for this kind of thing. That should still fall into your HTML and CSS only requirement, since SVG is valid HTML. There are tons of generators and tutorials out there.

    Solution 2: Add some divider elements into to your chart. This is a bit of a hacky solution, but it works. Here's an example: https://codepen.io/davidleininger/pen/abKJOOo/699fb1595f469e69054e36b27280344a

    Basically, you'd update your HTML to include dividers and give them a CSS custom property. Then you use those custom properties to generate divider lines in your chart:

    <div class="pie-chart">
      <div class="divider" style="--precent: 45;"></div>
      <div class="divider" style="--precent: 65;"></div>
      <div class="divider" style="--precent: 75;"></div>
      <div class="divider" style="--precent: 100;"></div>
    </div>
    

    After adding the dividers to your HTML, add this to your CSS, and you've got yourself some divider lines:

    .pie-chart .divider {
      background: white;
      height: 50%;
      left: 50%;
      margin-left: -1px;
      position: absolute;
      top: 0;
      transform-origin: 0 100%;
      transform: rotate(calc(1turn * (var(--precent) / 100)));
      width: 2px;
    }
    

    The transform is doing the heavy lifting here. It's calculating the position of all of the divider lines and rotating them to the correct position.