Share of the total

Each weight’s share of the weights’ total, as a percent: here the first item’s.

In CSS, flex divides a fixed width in proportion to each item’s weight, so the total is never written down. The query container is one of the items, with its own weight, and what is inside it reads its width.

Example

Result
Markup
<div class="share-of-the-total">
  <b style="--value: 4"><output></output></b>
  <i style="--value: 1"></i>
  <i style="--value: 3"></i>
  <i style="--value: 2"></i>
</div>
CSS
@property --result { syntax: '<integer>'; inherits: true; initial-value: 0; }
.share-of-the-total output::after { counter-reset: result var(--result); content: counter(result); }
.share-of-the-total { display: flex; width: 400px; flex: none; }
.share-of-the-total > * { flex: var(--value) 1 0px; min-width: 0; }
.share-of-the-total > b { container-type: inline-size; }
.share-of-the-total > b > output { --result: round(100cqw / 400px * 100); }

Limits

  • the row’s width written into the formula (400px here)
  • a flex-basis of 0
  • weights of 0 or more that add up to at least 1: under 1, flex leaves part of the row empty
  • no margins, padding or borders on the items, and no gap on the row: flex shares what is left after them
  • no item held by a minimum or maximum size (min-width: 0 keeps text from widening one)
  • whole percents: the read rounds, and an exact half can round down, 57.5% to 57 (of the 260 halves with a total up to 200: 8 in Chrome 155, 1 in WebKit 26.4, none in Firefox 158)
  • the example at its own width as a flex item (flex: none here): a flex row shrinks it, and the read with it
  • 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

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.