- Making Charts with CSS
- 23 CSS Charts And Graphs
- Related Articles
- Author
- Links
- Made with
- About a code
- CSS-only Pie Charts
- Author
- Links
- Made with
- About a code
- Skills Chart Animation with a Bit of Houdini Magic
- Author
- Links
- Made with
- About a code
- Pure CSS Area Chart
- Author
- Links
- Made with
- About a code
- Graph
- Author
- Links
- Made with
- About a code
- Pure CSS Donut Charts
- Author
- Links
- Made with
- About a code
- Pure CSS Background Depending on Height
- Author
- Links
- Made with
- About a code
- HTML Chart
- Author
- Links
- Made with
- About a code
- This Pen is 19% HTML & 81% CSS
- Author
- Links
- Made with
- About a code
- Purple Pie Chart
- Author
- Links
- Made with
- About a code
- Statistics Card
- Author
- Links
- Made with
- About a code
- CSS Animation: A Line Graph
- Author
- Links
- Made with
- About a code
- Interactive, Responsive Pie Chart
- Author
- Links
- Made with
- About a code
- Simple and Responsive Organizational Chart
- Author
- Links
- Made with
- About a code
- Bar Graph
- Author
- Links
- Made with
- About a code
- Charles Hayter’s Colour Diagrams
- Author
- Links
- Made with
- About a code
- Diagram
- Author
- Links
- Made with
- About a code
- Interactive SVG & CSS Graph
- Author
- Links
- Made with
- About a code
- Animated CSS Graph
- Author
- Links
- Made with
- About a code
- chart.css
- Author
- Links
- Made with
- About a code
- Pure CSS Bars
- Author
- Links
- Made with
- About a code
- CSS Only 3D Bar Graph
- Author
- Links
- Made with
- About a code
- Circle Chart With Three Bars
- Author
- Построение графиков на css
Making Charts with CSS
There are many ways to make visual representations of data: bar charts, line graphs, scatter diagrams, sparklines… not to mention the many ways in which you can implement them on the web. In this post I’ll be looking at plain CSS methods for styling data. But before we take a look at some examples, I think it’s worth briefly going over our design goals first.
Guidelines for Chart Making
- Accessibility: everyone should be able to view some format of the data we present, even if it’s a boring table (boring is better than nothing).
- Ease of development: graph-making shouldn’t be unnecessarily complex, and we’ll certainly want to avoid technical debt for the future.
- Performance: we need to make sure that users don’t spend a lot of time waiting for assets to download or for elements to be painted to the screen.
These goals are likely to change depending on the type of chart that make, as performance is going to be less of a concern for a static bar chart than a crazy interactive map. With these guidelines in mind, let’s look at a few examples.
There are a couple of ways to make a simple bar chart in CSS. For starters we’ll use a definition list for our data:
- A title of the graph
- Data 1: 20%
- Data 2: 50%
- Data 3: 30%
We’ll absolutely position the text content of each dd to the left with that span.
To make the “bars” that visually represent the data, we’ll use pseudo elements. To do that we could update the markup with classes like .percentage-20 , and set a width on its pseudo element:
.percentage:after < content: ""; display: block; background-color: #3d9970; >.percentage-20:after < width: 20%; >.percentage-30:after
But we don’t want to have to write out every single one of these classes by hand because the data is likely to change in the future. We could write a Sass loop to make all those classes for us:
@for $i from 1 through 100 < .percentage-#:after < $value: ($i * 1%); width: $value; >>
That’s a little icky as it’ll create a whole bunch of classes that we probably won’t be using in the final implementation, but there are lots of tools to tidy this up for us in production.
Next, we can add those classes we’ve automatically generated to each .percentage element, like so:
- A title of the graph
- IE 11: 7%
- Chrome: 20%
- Android 4.4: 2%
Finally we can add rules to the background of each .percentage element to aid legibility in comparing these values with a repeating-linear-gradient :
This technique is relatively simple, but I can’t help but think that this information should always be set in a table by default. Although I’m a little wary of styling tables in this way, that certainly doesn’t mean it’s impossible. For instance, Eric Meyer wrote about this technique and described how to position finicky table elements to behave like a bar chart. This is his original markup for the table:
Quarterly Results Invoiced Collected Q1 $18,450.00
$16,500.00
Q2 $34,340.72
$32,340.72
Q3 $43,145.52
$32,225.52
Q4 $18,415.96
$32,425.00
Unlike the example I used earlier, where I implemented a number of automatically generated helper classes in Sass to define the width of the bar charts, Eric used inline styles on the td element with those values being calculated server side or with JavaScript, rather than added by hand.
The example below is my copy of Eric’s original example where I’ve updated the styling a little bit:
I really like that each row in the table has a header such as Q1, Q2, etc. — that feels really neat and tidy rather than depending on a definition list to describe the content. They’re easy to position and will fall back nicely to a standard table if the CSS fails to load for whatever reason.
However, one of the problems with this approach is that it requires absolutely positioning each table row side by side, which means that if we want to add more data then we’ll need to do a lot more work than simply updating the markup. This means it could be a pain to work with in the future.
We don’t always have to use table s when representing information like this. That’s probably the case when we make a series of sparklines, tiny graphs that sit next to a line of text and help readers get a quick overview of the information. Wilson Miner outlined this method and made sure to focus on the accessibility of the information beforehand:
I’ve updated the original markup from what Wilson used since to me this feels like it should fit into a figure , as the docs on MDN state that:
Usually [a figure]… is an image, an illustration, a diagram, a code snippet, or a schema that is referenced in the main text, but that can be moved to another page or to an appendix without affecting the main flow.
That makes a lot more sense to me than a plain ul element. But anyway, here’s what that looks like without any CSS:
Very accessible! Next up we can add styles to that sparkline element and position it to the right of the link with inline-block. And again, we could use that Sass class generator we used earlier to set the height of each bar. But, let’s keep those styles inline just for now:
Make sure to hover over each entry in the list to see an expanded version of the diagram that I’ve added. Although it’s not particularly helpful in terms of breaking down the data, it shows that we aren’t stuck with charts in one single representation; manipulating these visualisations with such ease is a great advantage when using simple markup and CSS.
Lea Verou recently wrote a great piece about making pie charts. One possibility she suggests is using pseudo elements that cover a circle and nudging them around with transform: rotate() .
Another possibility is SVG, which has a number of advantages, some of which we’ll list in the next section.
If browsers supported conic-gradient() , that would be a very compelling way to create them. They don’t quite yet, but Lea has a polyfill for it that works wonderfully. Here’s a pie chart demo using it that we made for one of the last polls we did here on CSS-Tricks:
Problems with making charts with CSS
- If you’re using background to style an element then it (probably) won’t be visible if the web page is printed. The only exception is if you use -webkit-print-color-adjust: exact; in a WebKit browser.
- Finicky control over design: absolutely positioning table rows, for instance, is likely to be pain for developers at some point in the future.
- Browser support is a laborious process in some instances, and ensuring that all devices support every CSS property might be difficult to test.
- It’s not possible to use inline styles on pseudo elements, so if you want to style a pseudo element with JavaScript then this makes things a bit more complicated.
- It’s possible to do anything with CSS, but when we’re making pure CSS line graphs we should probably take a little while to reconsider the implications that this might have on the rest of the codebase.
Plain CSS and markup solutions for charts and graphs work to a certain extent, and in many situations they’re probably the safest bet. But I think it’s worth exploring alternative solutions to representing data.
In the next post in this series I’ll be looking at SVG and JavaScript solutions to making charts.
23 CSS Charts And Graphs
Collection of free HTML and pure CSS chart and graph code examples from Codepen and other resources.
Related Articles
- jQuery Charts And Graphs
- Tailwind Charts And Graphs
Author
Links
Made with
About a code
CSS-only Pie Charts
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Links
Made with
About a code
Skills Chart Animation with a Bit of Houdini Magic
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Links
Made with
About a code
Pure CSS Area Chart
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Links
Made with
About a code
Graph
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Links
Made with
About a code
Pure CSS Donut Charts
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Links
Made with
About a code
Pure CSS Background Depending on Height
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Links
Made with
About a code
HTML Chart
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Links
Made with
About a code
This Pen is 19% HTML & 81% CSS
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Links
Made with
About a code
Purple Pie Chart
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Links
Made with
About a code
Statistics Card
Financial chart UI design, animated SVG line. Tooltips on hover. No jQuery, no JavaScript involved.
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Links
Made with
About a code
CSS Animation: A Line Graph
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Dependencies: simple-line-icons.css, jquery.js
Author
Links
Made with
About a code
Interactive, Responsive Pie Chart
Interactive, responsive pie chart with conic-gradient() , CSS variables & Houdini magic.
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Links
Made with
About a code
Simple and Responsive Organizational Chart
HTML5 and CSS3 only simple and responsive organizational chart.
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Links
Made with
About a code
Bar Graph
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Links
Made with
About a code
Charles Hayter’s Colour Diagrams
An attempt to recreate the colour diagrams in Charles Hayter’s “A New Practical Treatise on the Three Primitive Colours Assumed as a Perfect System of Rudimentary Information”.
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Links
Made with
About a code
Diagram
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Links
Made with
About a code
Interactive SVG & CSS Graph
Interactive SVG & CSS graph with segments, legend and hover effect.
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Links
Made with
About a code
Animated CSS Graph
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Links
Made with
About a code
chart.css
A simple CSS chart system.
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Links
Made with
About a code
Pure CSS Bars
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Links
Made with
About a code
CSS Only 3D Bar Graph
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Links
Made with
About a code
Circle Chart With Three Bars
Compatible browsers: Chrome, Edge, Firefox, Opera, Safari
Author
Построение графиков на css
Отладка кода вдвое сложнее, чем его написание. Так что если вы пишете код настолько умно, насколько можете, то вы по определению недостаточно сообразительны, чтобы его отлаживать.
Все, что мы делаем в программировании — это частный случай чего-то более общего, и зачастую мы осознаем это чересчур быстро.
Работу программистов следует оценивать не по их изобретательности и логике, а по полноте анализа каждой ситуации.
Люди считают, что программирование — это наука избранных, но в реальности все наоборот — просто много людей создают программы, которые используют чужие программы, как-будто строя стену из маленьких кирпичиков.
Вебмастера не должны строить свою жизнь вокруг трафика с Яндекса. Это не должно быть вопросом жизни и смерти сайта.
Большинство хороших программистов делают свою работу не потому, что ожидают оплаты или признания, а потому что получают удовольствие от программирования.
PHP — это маленькое зло, созданное некомпетентными новичками, в то время как Perl — это большое и коварное зло, созданное умелыми, но извращёнными профессионалами.
Подумайте, сколько психических сил потрачено на поиски коренного различия между «алгоритмом» и «программой».
Есть два способа создания дизайна программы. Один из них, это сделать его настолько простым, что в нем, очевидно, не будет недостатков. Другой способ — сделать его настолько запутанным, что в нем не будет очевидных недостатков.
Инженер как врач общается с телом, программист как священник — с душой компьютера, а системный администратор как медсестра — поддерживает стабильное состояние.
Если называть Python заменой BASIC, то тогда и трансформер Optimus Prime — это только замена грузовика.
Обработать ошибку легко: Постарайтесь исправить программу. Удачный запуск тоже легко обработать: Вы решили не ту задачу. Постарайтесь исправить и эту ошибку.
Всегда пишите код так, будто сопровождать его будет склонный к насилию психопат, который знает, где вы живете.