Displaying Progress Bar Label Value Attribute with ::before Pseudo-Element

Abstract: Display progress bar label and value using CSS attr() with ::before pseudo-element.

Created: 2026-08-01 by
You can display the label and value attribute of a progress bar using the CSS ::before pseudo-element by leveraging the attr() function within the content property. This technique allows you to dynamically inject text content from an HTML element's attributes directly into the stylesheet without modifying the DOM structure or adding extra markup elements. By combining this with standard positioning and styling, you create a clean, accessible progress indicator that updates automatically as the value changes.

Understanding the attr() Function

The core mechanism behind this solution is the attr() function in CSS. While traditionally used for image sources in background-image, modern browsers support its use in the content property of pseudo-elements like ::before and ::after. This function extracts the value of a specified attribute from the target element and inserts it as a string.

For a progress bar, we typically want to show both the current value (e.g., "50") and potentially a label (e.g., "Progress:"). Since the <progress> element does not have a native value attribute that reflects the current state in a way that is easily readable via attr() for dynamic updates in all contexts, we often rely on custom data attributes or simply style the existing structure. However, a more robust approach involves using a div with a custom attribute or utilizing the aria-valuenow if supported, but the most common and reliable method for visual labels is using a custom attribute like data-value or relying on the fact that some implementations allow direct attribute reading.

In many practical scenarios, developers set a custom attribute such as data-label="Loading..." and data-current="75" on the progress container. The CSS then reads these values. Note that standard <progress> elements do not expose their internal current value via HTML attributes in a static way, so this method is best applied to styled divs acting as progress bars or when manually updating a data attribute via JavaScript.

Implementing the Basic Structure

To begin, create a simple HTML structure. You will need a container element that represents the progress bar. For this example, we will use a div with specific data attributes to hold our label and value information.

<div class="progress-bar" data-label="Upload Progress" data-value="60">
  <div class="progress-fill" style="width: 60%"></div>
</div>

Here, the outer div holds the metadata we want to display. The inner div handles the visual width. The CSS will target the outer div to generate the text.

CSS Implementation Details

The CSS rules are straightforward but require attention to positioning and content generation. We need to position the pseudo-element relative to the progress bar and ensure it sits above or beside the bar itself.

.progress-bar {
  position: relative;
  width: 100%;
  height: 20px;
  background-color: #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
}

.progress-bar::before {
  content: attr(data-label) ": " attr(data-value) "%";
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: white;
  font-size: 12px;
  font-weight: bold;
  z-index: 10;
}

In this code block, position: relative on the parent establishes a containing block for the absolutely positioned pseudo-element. The content property concatenates the label and value using standard string syntax inside the attr() calls. The transform: translate(-50%, -50%) ensures the text is perfectly centered over the bar, regardless of the bar's width.

Handling Dynamic Updates

If your progress bar is driven by JavaScript, you must update the data-value attribute whenever the progress changes. Browsers re-evaluate attr() in the content property when the attribute changes, ensuring the displayed text stays in sync with the visual bar.

// Example JavaScript snippet
const progressBar = document.querySelector('.progress-bar');
let currentProgress = 0;

function updateProgress(value) {
  currentProgress = value;
  progressBar.setAttribute('data-value', currentProgress);
  progressBar.querySelector('.progress-fill').style.width = currentProgress + '%';
}

This approach avoids the need for additional HTML elements like <span> tags to hold the text, keeping the DOM clean. It also ensures that screen readers can still access the underlying semantic meaning if you maintain proper ARIA roles, although purely visual labels should be handled carefully for accessibility.

Browser Compatibility and Limitations

The attr() function in content is widely supported in modern browsers, including Chrome, Firefox, Safari, and Edge. It works consistently in Brave v1.61.109 and other Chromium-based browsers. However, there are limitations:

  • Attribute Types: attr() only works with string attributes. Numeric attributes are converted to strings, which is usually desired.
  • Dynamic Styles: Some older browsers may not recalculate content immediately upon attribute change without a forced reflow, though modern engines handle this efficiently.
  • Semantic Elements: As noted, <progress> elements themselves don't have a value attribute that reflects the current state statically. If you must use <progress>, consider wrapping it in a div with data attributes for the label, as shown above.

For those interested in related styling techniques, you might find Extending Functionality: Updating CSS Props with Input Range Sliders useful, as it shares similar principles of styling form-like controls with custom CSS properties.

Frequently Asked Questions

Can I use attr() to read the actual value of a standard <progress> element?

No, the <progress> element does not expose its current animated value through a static HTML attribute that attr() can read. You must use a wrapper div with a data-value attribute that you update via JavaScript alongside the progress bar's visual state.

Why is my pseudo-element text not updating when I change the data attribute?

This usually happens because the browser has cached the computed style. Ensure you are actually changing the attribute in the DOM, not just the CSS variable. In rare cases, triggering a reflow by toggling a class on the parent element can force the browser to recalculate the content property.

Does this method work for accessibility tools like screen readers?

Pseudo-element content generated via content is generally ignored by screen readers. To maintain accessibility, ensure the progress bar has appropriate ARIA attributes like role="progressbar" and aria-valuenow on the visible element, rather than relying solely on the visual label provided by ::before.

How do I center the text vertically if the progress bar height changes?

Using top: 50% combined with transform: translateY(-50%) is the most robust method. This ensures the text remains vertically centered relative to the progress bar's height, even if you adjust the height property later in your CSS.

Are there performance concerns with using attr() in content?

Performance is generally not an issue unless you are animating the attribute value thousands of times per second. For typical UI updates, the overhead is negligible. However, avoid using complex selectors or excessive pseudo-elements on large lists, as the browser must recalculate content for each instance.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More