• About Us
  • Privacy Policy
  • Disclaimer
  • Contact Us
AimactGrow
  • Home
  • Technology
  • AI
  • SEO
  • Coding
  • Gaming
  • Cybersecurity
  • Digital marketing
No Result
View All Result
  • Home
  • Technology
  • AI
  • SEO
  • Coding
  • Gaming
  • Cybersecurity
  • Digital marketing
No Result
View All Result
AimactGrow
No Result
View All Result

One other Stab on the Excellent CSS Pie Chart… Sans JavaScript!

Admin by Admin
June 4, 2026
Home Coding
Share on FacebookShare on Twitter


Not too long ago, Juan Diego Rodríguez revealed a wonderful article exploring how far CSS may be pushed to construct a semantic and customizable pie chart whereas conserving JavaScript to a minimal.

Citing Juan himself:

On this article, we’ll attempt making the right pie chart in CSS. Meaning avoiding as a lot JavaScript as attainable whereas addressing main complications that comes with handwriting pie charts.

And it acknowledged some targets that I need to undergo once more so as of precedence:

  • This should be semantic! That means a display screen reader ought to be capable of perceive the info proven within the pie chart.

To my understanding, the unique article’s answer reached that aim. Its semantic strategy (labels in plain HTML + values as attributes reinjected into the DOM through pseudo-elements) is clear, expressive, and hopefully accessible.

  • This needs to be HTML-customizable! As soon as the CSS is finished, we solely have to vary the markup to customise the pie chart.

The unique article reached that aim as nicely.

  • This could hold JavaScript to a minimal! No downside with JavaScript typically, it’s simply extra enjoyable this manner.

The unique article aimed to make use of as little JavaScript as attainable, primarily for enjoyable. I are likely to disagree barely. For me, it shouldn’t be only for enjoyable, since…

  • JavaScript is there to take care of states and logic, and
  • CSS is there to type the markup.

The preliminary “no JavaScript” constraint was significant to me. CSS needs to be highly effective sufficient to allow us to type a pie chart. JavaScript shouldn’t be required. So, I made a decision to see whether or not there was a strategy to 100% do away with it and, for enjoyable, forked the article’s CodePen throughout a lunch break.

I stored the unique code as unchanged as attainable, preserving its semantic strategy and HTML-side customizability. If It Ain’t Broke, Don’t Repair It™.

Coincidentally, this text got here proper after a latest brief pen of mine toying with bar charts. So I used to be already within the temper for charts. However bar charts are far simpler: every bar’s place or dimension doesn’t depend upon the others. A pie chart is a unique beast: every slice’s place is determined by the earlier one. Fortunately, this made it extra of a enjoyable problem.

However earlier than diving into my tackle pie charts, let’s see how these have been approached by different internet builders.

Prior Artwork

I learn many blogs, articles, and code examples from skilled front-end builders, however I’m not one myself, so I’m not completely sure of my potential to determine probably the most related and up-to-date prior artwork… Let’s attempt anyway.

It’s simple to seek out many JavaScript libraries coping with charts. I’ve used them quite a bit in my work. Nevertheless, resulting from our no-JavaScript constraint, we will exclude them.

I began searching for CSS-only pie charts, and one of many first libraries that pops up is Chart-CSS. It advertises semantic construction, HTML tags to show information, accessibility, and uncooked information contained in the markup. It appears to be an excellent library and doesn’t use any JavaScript.

As a substitute, it makes use of HTML tables, which, in my view and expertise, makes whole sense (more often than not, supply information is available in a desk). Nevertheless, it doesn’t resolve the particular problem of letting the consumer set solely the values whereas having the beginning and finish angles of every slice routinely computed. On this case, customers nonetheless should manually outline them.

There are additionally excellent articles discussing charts or information visualization typically. To call a number of:

They simply have one small (however crucial to us) disadvantage. Whereas these assets are beneficial in explaining how chart accessibility ought to work, they don’t actually tackle simple HTML “interface” nor pure CSS implementations.

How I Tackled the Drawback

In case you are nonetheless studying, I assume you might be a minimum of considerably eager about my strategy. Understandably, If you happen to simply need to see the code, right here it’s!

Initially, the explanation JavaScript was required was that every slice wanted to know the worth of the earlier one. Nevertheless, resulting from how CSS property inheritance works, a baby can’t know the state of one other little one. Regardless of figuring out this, I first tried to find out whether or not there have been area of interest or “voodoo” strategies that may permit me to maintain the unique HTML markup and attribute-based strategy whereas eradicating JavaScript.

I do know that folks like Roman Komarov can do unimaginable issues with CSS, so I even thought-about exploring strategies involving property animations. However I clearly didn’t have the time to research that route.

I returned to the core challenge: due to how CSS inheritance works, kids can’t know the state of their siblings. I clearly wanted a “surrounding entity” to deal with this.

In Juan’s put up, that “entity” was JavaScript, which may loop by way of all kids and compute the suitable slice accumulations.

const pieChartItems = doc.querySelectorAll(".pie-chart li");

let accum = 0;

pieChartItems.forEach((merchandise) => {
  merchandise.type.setProperty("--accum", accum);
  accum += parseFloat(merchandise.getAttribute("data-percentage"));
});

The JavaScript code units an --accum worth for every slice, which holds the share values of all charts previous to it. With out it, we wouldn’t know the place to place every slice and its corresponding label.

In HTML/CSS, that entity exists too: the traditional mother or father component. Subsequently, my answer was to maneuver the share values to the mother or father.

First, let’s keep in mind what the unique markup for the pie chart seemed like this:

  • Apple
  • Banana
  • Orange
  • Strawberry

Whereas the model we’ll be utilizing appears like this:

  • Apple
  • Banana
  • Orange
  • Strawberry

We’ve moved all values to the mother or father and given every merchandise a devoted identify — successfully indexing them.

I had beforehand experimented with this type of “indexing” CSS workaround, for instance, to compensate for the shortage of sibling-index() and sibling-count() capabilities to generate random numbers. I knew this was the best route and that the remainder would comply with logically on the CSS aspect.

Spoiler: sibling-index() and sibling-count() have gotten Baseline quickly!

It could appear like duplication since we didn’t add something however reasonably moved the attributes. Nevertheless, this slight change permits us to handle all labels and values from the mother or father in CSS. What’s finest, we nonetheless hold all attributes shut collectively. And when you might say that this received’t scale as nicely, if we’ve got information with tons of entries, then a pie chart is never the only option to point out it.

Optionally, we may add data-label attributes to the labels simply to pair labels and values visually.

  • Apple
  • Banana
  • Orange
  • Strawberry

Now let’s study the CSS. The implementation requires two units of some repetitive however simple CSS guidelines.

Firstly, we’ll must move down every share to its corresponding slice. To take action, we use Juan’s and get the data-percentage attributes into CSS by way of the upgraded attr() operate. In parallel, we’ll assign them to the corresponding slice utilizing the nth-child() selector.

.pie-chart {
   /* We write one for every slice we expect we'll want */
  --p-100-1: attr(data-percentage-1 kind()); :nth-child(1) { --p-100: var(--p-100-1) }
  --p-100-2: attr(data-percentage-2 kind()); :nth-child(2) { --p-100: var(--p-100-2) }
  --p-100-3: attr(data-percentage-3 kind()); :nth-child(3) { --p-100: var(--p-100-3) }
  --p-100-4: attr(data-percentage-4 kind()); :nth-child(4) { --p-100: var(--p-100-4) }
   /*...*/
}

For that form of repetitive/incremental code, I hold it as a one-liner with out carriage return. IMHO it’s a really acceptable exception to frequent formatting guidelines because it prevents typos by easing scan-ability of and likewise eases additional iterations (e.g., including help for extra slices). However your mileage might fluctuate.

Let’s look somewhat nearer at what’s happening right here. On the stage of the entire pie, we entry the chances for every slice by way of their index and retailer them in a corresponding CSS variable, so the fourth component will get --p-100-4, the fifth component will get --p-100-5, and so forth:

--p-100-4: attr(data-percentage-4 kind());

Subsequent, we move every a --p-100 variable that’s native to every slice.

:nth-child(4) {
  --p-100: var(--p-100-4);
}

We now have all these slice values accessible at two ranges:

  • On the pie, through listed variables: --p-100-1, --p-100-2, --p-100-3
  • On every slice, through the --p-100 variable

Now, we’ll must calculate the corresponding --accum worth, which is the sum of the values of all earlier slices. To take action, we’ll should progressively sum every share after every slice, then assign the worth to the slice utilizing nth-child() once more.

.pie-chart {
  /* ... */
  --accum-1: 0;                                     :nth-child(1) { --accum: var(--accum-1) }
  --accum-2: calc(var(--accum-1) + var(--p-100-1)); :nth-child(2) { --accum: var(--accum-2) }
  --accum-3: calc(var(--accum-2) + var(--p-100-2)); :nth-child(3) { --accum: var(--accum-3) }
  --accum-4: calc(var(--accum-3) + var(--p-100-3)); :nth-child(4) { --accum: var(--accum-4) }
  /*...*/
}

Once more, we first work on the pie stage, the place we compute one devoted variable per slice. The primary slice is a particular case: there isn’t a earlier slice, so the buildup is 0. Whereas in the remainder, the buildup for the slice n is the buildup of the slices earlier than n−1 plus the worth of the slice n−1.

--accum-4: calc(var(--accum-3) + var(--p-100-3));

The fourth component will get --accum-4, the fifth component will get --accum-5, and so forth. Simply as the chances, on the stage of every slice, we assign them to the native variable --accum.

:nth-child(4) {
  --accum: var(--accum-4);
}

As soon as once more, we’ve got all these slice accumulation values accessible at two ranges:

  • On the pie, through listed variables: --accum-1, --accum-2, --accum-3
  • On every slice, through the --accum variable

I hope future native CSS options (maybe @operate?) will stop us from having to resort to such repetitive code. Within the meantime, this may be simplified with a CSS preprocessor (Sass, Much less).

Whereas forking the unique Pen, some questions popped out in my thoughts — that I didn’t truly discover — to maintain the unique code as unchanged as attainable:

  • What about utilizing  and  for labels and values?
  • What about utilizing a 
     (since charts are sometimes extracted from tables with rows like [label, value])?

    Word About Accessibility

    In my fork, I dealt with accessibility the identical method Juan did, however with one slight modification: I used counter-reset / counter() as an alternative of attr() to assign the chances to the content material property. This could work simply nearly as good as attr(), however let’s ensure that it's nonetheless screenreader-friendly:

    One other factor I considered altering was the label parts inside every 

  • . Within the unique article, Juan makes use of a  component, whereas I opted for  as an alternative. Nevertheless, I feel it might be completely acceptable to make use of the  itself. We usually consider them as being bounded inside  parts, however the spec says that we may anticipate to make use of them in contexts “the place phrasing content material is anticipated.” So I couldn't discover any obligation to make use of them solely within the context of types.

    Default Colours

    Juan’s article additionally known as upon some enhancements, which I attempted to handle in my fork:

    • data-color may be omitted, and colours are then generated.
    • Colours may be outlined both on the mother or father or on the kids (consumer’s alternative; each are supported).

    This interprets to the subsequent snippet for every slice:

    .pie-chart li {
      --color: attr(data-color kind());
      --bg-color: var(--color, hsl(calc(360deg * sibling-index() / sibling-count()) 90% 40%));
    }

    I avoided utilizing sibling-index() and sibling-count() in the principle half, since they aren’t Baseline (but, however quickly!), however I couldn’t maintain myself again since calculating the colour hue is a lot fancier with them. These capabilities actually permit some magic!

    Nonetheless, right here is my “CSS-only polyfill”; repetitive (but easy) code:

    .pie-chart {
      :has(:nth-child(1)) { --sibling-count: 1 } :nth-child(1) { --sibling-index: 1; }
      :has(:nth-child(2)) { --sibling-count: 2 } :nth-child(2) { --sibling-index: 2; }
      :has(:nth-child(3)) { --sibling-count: 3 } :nth-child(3) { --sibling-index: 3; }
      :has(:nth-child(4)) { --sibling-count: 4 } :nth-child(4) { --sibling-index: 4; }
      /* ... */
    }

    Extra Chart Varieties?

    We now have a typical basis for different chart sorts. As a proof of idea, I applied a bar chart mode in my fork.

    A Internet Element, Maybe?

    In a method, we have already got an online part right here — one with out JavaScript, utilizing mild DOM.

    And to me  is just not essentially totally different that both 

     or 

    . I can see worth on this strategy when contemplating progressive enhancement, although.

    For instance, a chart that refreshes routinely and fetches dwell information. However that may require JavaScript — which we're intentionally avoiding as we speak.

Tags: ChartCSSJavaScriptperfectPieSansStab
Admin

Admin

Next Post
Prepared Your Clown Noses: The Sport Reveals We Hold Hoping For Forward Of SGF 2026

Prepared Your Clown Noses: The Sport Reveals We Hold Hoping For Forward Of SGF 2026

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recommended.

Methods to Unlock Act 2: The Desert in Mewgenics

Methods to Unlock Act 2: The Desert in Mewgenics

February 16, 2026
Infostealer Steals OpenClaw AI Agent Configuration Recordsdata and Gateway Tokens

Infostealer Steals OpenClaw AI Agent Configuration Recordsdata and Gateway Tokens

February 17, 2026

Trending.

Nsfw Chatgpt Options – Examples I’ve Used

Nsfw Chatgpt Options – Examples I’ve Used

October 13, 2025
The Obtain: the tech reshaping IVF and the rise of balcony photo voltaic

The Obtain: the tech reshaping IVF and the rise of balcony photo voltaic

May 7, 2026
Undertaking possession (fairness and fairness)

Your work diary | Seth’s Weblog

May 6, 2026
From Shader Uniforms to Clip-Path Wipes: How GSAP Drives My Portfolio

From Shader Uniforms to Clip-Path Wipes: How GSAP Drives My Portfolio

May 7, 2026
I Used Each and This is How They Differ

I Used Each and This is How They Differ

May 7, 2026

AimactGrow

Welcome to AimactGrow, your ultimate source for all things technology! Our mission is to provide insightful, up-to-date content on the latest advancements in technology, coding, gaming, digital marketing, SEO, cybersecurity, and artificial intelligence (AI).

Categories

  • AI
  • Coding
  • Cybersecurity
  • Digital marketing
  • Gaming
  • SEO
  • Technology

Recent News

iFood Confirms Knowledge Breach Affecting 1.2 Million Customers in Brazil

iFood Confirms Knowledge Breach Affecting 1.2 Million Customers in Brazil

June 5, 2026
Crypto Lead Era Companies in Miami

Crypto Lead Era Companies in Miami

June 5, 2026
  • About Us
  • Privacy Policy
  • Disclaimer
  • Contact Us

© 2025 https://blog.aimactgrow.com/ - All Rights Reserved

No Result
View All Result
  • Home
  • Technology
  • AI
  • SEO
  • Coding
  • Gaming
  • Cybersecurity
  • Digital marketing

© 2025 https://blog.aimactgrow.com/ - All Rights Reserved