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
- Reads the
valueattribute from the<data>element and parses it as bytes - Stores the original text content as a
titleattribute (visible on hover) - Divides by 1024 (or 1000 for decimal) to find the best unit
- Formats the numeric part using
Intl.NumberFormatfor locale-aware digits - 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) |
|---|---|---|
| B | 1 | 1 |
| KB | 1,024 | 1,000 |
| MB | 1,048,576 | 1,000,000 |
| GB | 1,073,741,824 | 1,000,000,000 |
| TB | 1,099,511,627,776 | 1,000,000,000,000 |
| PB | 1,125,899,906,842,624 | 1,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:
| File | Size |
|---|---|
| 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.
Progressive Enhancement
The <data> element's original text serves as a fallback when JavaScript is unavailable. Write a reasonable pre-formatted value as the text content.
Accessibility
- The original text is preserved as a
titleattribute, accessible on hover - The semantic
<data>element withvalueattribute 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