Home >Web Front-end >CSS Tutorial >How Can I Create a Percentage Pie Chart Using Only CSS?

How Can I Create a Percentage Pie Chart Using Only CSS?

Barbara Streisand
Barbara StreisandOriginal
2024-12-26 14:54:17813browse

How Can I Create a Percentage Pie Chart Using Only CSS?

Percent Pie Chart with CSS Only

Creating static, pie-shaped elements solely using CSS requires an understanding of specific CSS properties.

Element #2 Creation

To create element #2, which represents a specific percentage, use the CSS property conic-gradient. This property creates a cone-shaped gradient, with the vertex positioned at the center of the parent element. The angle of the cone is determined by the percentage value, with 100% representing a full circle.

Percentage Value Management

To manage the shape of element #2 for varying percentages, utilize a combination of CSS properties:

  • conic-gradient: Adjust the angle of the cone to match the percentage.
  • clip-path: Use a circular clip-path to limit the visible area of the conic-gradient. This ensures that the shape appears correctly for both small and large percentages.

Animation

To animate the pie chart, employ the animation property and define a from state that sets the percentage to 0. By gradually increasing the percentage value, the pie chart will fill up incrementally.

Rounded Edges

To achieve rounded edges, use radial-gradient with two color stops. The first stop at 98% creates a subtle highlight, while the second stop at 100% uses #0000 to create a sharp boundary. A mask or -webkit-mask is applied to selectively hide portions of the gradient.

Sample Code

.pie {
  --p: 20;
  --b: 22px;
  --c: darkred;
  --w: 150px;
  
  width: var(--w);
  aspect-ratio: 1/1;
  position: relative;
  display: inline-grid;
  margin: 5px;
  place-content: center;
  font-size: 25px;
  font-weight: bold;
  font-family: sans-serif;
}

.pie:before {
  content: "";
  position: absolute;
  border-radius: 50%;
  background:
    radial-gradient(farthest-side, var(--c) 98%, #0000) top/var(--b) var(--b) no-repeat,
    conic-gradient(var(--c) calc(var(--p)*1%), #0000 0);
  mask: radial-gradient(farthest-side, #0000 calc(99% - var(--b)), #000 calc(100% - var(--b)));
}

.pie:after {
  inset: calc(50% - var(--b)/2);
  background: var(--c);
  transform: rotate(calc(var(--p)*3.6deg - 90deg)) translate(calc(var(--w)/2 - 50%));
}

The above is the detailed content of How Can I Create a Percentage Pie Chart Using Only CSS?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn