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
contentimmediately upon attribute change without a forced reflow, though modern engines handle this efficiently. - Semantic Elements: As noted,
<progress>elements themselves don't have avalueattribute that reflects the current state statically. If you must use<progress>, consider wrapping it in adivwith 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.