使用现代函数的 CSS 柱状图

New CSS features can sometimes make it easier and more efficient to code designs we already knew how to create. This efficiency could stem from reduced code or hacks, or improved readability due to the new features.

新的 CSS 特性有时可以让编码我们已经知道如何创建的设计变得更容易和更高效。这种高效可能来自于减少代码或 hack,或者由于新特性而提高的可读性。

In that spirit, let’s revamp what’s under the hood of a bar chart.

本着这种精神,让我们重构一下条形图的内部机制。

<ul class="chart" tabindex="0" role="list" aria-labelledby="chart-title"> <li class="chart-bar" data-value="32" tabindex="0" role="img" aria-label="32 percentage">32%</li> </ul>

We begin by laying out a grid.

我们从布局一个网格开始。

.chart { display: grid; grid-template-rows: repeat(100, 1fr); }

The chart metric is based on percentage, as in “some number out of 100.” Let’s say we’re working with a grid containing 100 rows. That ought to stress test it, right?

图表的度量基于百分比,即“某个数字占 100”。假设我们使用一个包含 100 行的网格。这应该能对其进行压力测试,对吧?

Next, we add the bars to the grid with the grid-column and grid-row properties:

接下来,我们使用 grid-columngrid-row 属性将条形添加到网格中:

.chart-bar { grid-column: sibling-index(); grid-row: span attr(data-value number); }

Right off the bat, I want to note a couple of things. First is that sibling-index() function. It’s brand new and has incomplete browser support as of this writing (come on, Firefox!), though it’s currently supported in the latest Chrome and Safari (but not on iOS apparently). Second is that attr() function. We’ve had it for a while, but it was recently upgraded and now accepts data-attributes. So when we have one of those in our markup — like data-value="32" — that’s something the function can read.

一开始,我想指出几点。首先是 sibling-index() 函数。它是全新的,目前浏览器支持还不完整browser support(加油,Firefox!),尽管在最新的 Chrome 和 Safari 中已有支持(但 iOS 上显然不支持)。其次是 attr() 函数。我们已经拥有它一段时间了,但它最近升级了,并且now accepts data-attributes。所以当我们的标记中有这样的属性——比如 data-value="32"——函数就可以读取它。

With those in place, that’s really all we need to create a pretty darn nice bar chart in vanilla CSS! The following demo has fallbacks in place so that you can still see the final result in case your br...

开通本站会员,查看完整译文。

Accueil - Wiki
Copyright © 2011-2026 iteam. Current version is 2.153.0. UTC+08:00, 2026-02-13 10:43
浙ICP备14020137号-1 $Carte des visiteurs$