count()

How many numbers a list has.

In CSS, a flex row of items each 1px wide, whatever their values, is as wide as there are items; an auto column holds the row, and a query container in it reads the width back.

Example

Result
Markup
<div class="count">
  <div>
    <i style="--value: 1"></i>
    <i style="--value: 2"></i>
  </div>
  <b><output></output></b>
</div>
CSS
@property --result { syntax: '<integer>'; inherits: true; initial-value: 0; }
.count output::after { counter-reset: result var(--result); content: counter(result); }
.count { display: inline-grid; width: max-content; grid-template-columns: auto; }
.count > div { display: flex; }
.count > div > i { flex: none; width: 1px; }
.count > b { container-type: inline-size; }
.count > b > output { --result: round(100cqw / 1px); }

dCSS Example

With dCSS, an element whose class is named after the function (dCSS’s docs).

Result
Markup
<link rel="stylesheet" href="dcss.css">
<link rel="stylesheet" href="families/array.css">

<figure class="dcss-count">
  <ul>
    <li style="--value: 1"></li>
    <li style="--value: 2"></li>
  </ul>
  <output></output>
</figure>

Limits

These are the Example’s; the dCSS Example’s are in dCSS’s docs.

  • every item counts, whatever its --value: d3.count skips items with no number
  • no gap between the items: a gap adds to the count
  • the grid at its natural width (width: max-content): a grid stretched by its parent, as an item of a grid or of a column flexbox, stretches its auto columns, and the read with them
  • no margins, padding or borders on the items or the query containers: they add to the widths read, and 100cqw reads the content box
  • each query container stretched across its track (justify-items and justify-self at their defaults): aligned to a side or the center, it shrinks to its content, none, and reads 0
  • no other registration of --result on the page: a later @property --result that doesn’t inherit leaves the read right and the counter at 0

Browser support

ChromeSafariFirefox
Example14026158
dCSS Example14026.2158

Each row gives the first versions that support every feature its example uses, by MDN’s browser-compat-data. The Example was run in Chrome 155, Safari’s WebKit 26.4 and Firefox 158, the dCSS Example in Chrome 155 and Safari’s WebKit 26.4.