data-format-bytes

Human-readable file size formatting. Add data-format-bytes to any <data> element for automatic byte formatting.

Overview

The data-format-bytes attribute enhances native <data> elements by replacing their text content with a human-readable file size string. Uses binary math (÷1024) by default with familiar units (KB, MB, GB).

How It Works

  1. Reads the value attribute from the <data> element and parses it as bytes
  2. Stores the original text content as a title attribute (visible on hover)
  3. Divides by 1024 (or 1000 for decimal) to find the best unit
  4. Formats the numeric part using Intl.NumberFormat for locale-aware digits
  5. Replaces the text with the formatted value and unit label

Attributes

Attribute Type Description
data-format-bytes string Decimal precision for the formatted value. Default "0" (no decimals). Use "1" or "2" for more detail.
value string The raw byte count. Standard HTML value attribute on <data>.
data-unit string "decimal" to use ÷1000 instead of ÷1024. Default is binary.
data-locale string Optional locale override (e.g., "de-DE"). Defaults to browser locale.
data-format-bytes-init boolean Set automatically to prevent double-binding. Do not set manually.

Precision

The attribute value controls decimal places in the output:

0 decimals (default): 1 MB

1 decimal: 1.5 MB

2 decimals: 5.00 GB

Binary vs. Decimal

By default, data-format-bytes uses binary math (÷1024), matching how operating systems report file sizes. Add data-unit="decimal" to use ÷1000 (how storage manufacturers report capacity).

Binary (default): 1 MB

Decimal: 1 MB

Unit Reference

Unit Binary (÷1024) Decimal (÷1000)
B11
KB1,0241,000
MB1,048,5761,000,000
GB1,073,741,8241,000,000,000
TB1,099,511,627,7761,000,000,000,000
PB1,125,899,906,842,6241,000,000,000,000,000

Locale Override

Use data-locale to format the numeric part in a specific locale:

German: 1,5 MB

Common Use Cases

File List

Display file sizes in a table. The font-variant-numeric: tabular-nums CSS ensures columns align:

FileSize
photo.jpg 3.0 MB
document.pdf 512.0 KB
video.mp4 1.0 GB

Dynamic Elements

Elements added to the DOM after page load are automatically enhanced via a MutationObserver. No manual initialization is needed.

Accessibility

  • The original text is preserved as a title attribute, accessible on hover
  • The semantic <data> element with value attribute provides machine-readable byte counts
  • Falls back to the original text content when JavaScript is unavailable
  • No wrapper element — the <data> is the enhanced element, keeping the accessibility tree clean