DEV Community

Michael Kennedy
Michael Kennedy

Posted on • Updated on

Colour Contrast of Overlapping Text Labels

When using the standard Bootstrap progress bar control, any text labels need to be centred over the individual bars. When there are multiple progress controls on-screen, this can look odd.

Multiple progress bars

If our text is particularly long, and the viewable area of the progress bar is particularly small, then we need to force a minimum width and carefully consider our wording. This can be tricky in a multi-lingual product.

Progress bar with small area

The easiest way to handle this, is by centring the text. Perhaps by superimposing an additional label over the control. However, such an approach is dependent on the text colour contrast when straddling two progress objects.

Centred text without changing text colour

The Bootstrap control typically doesn't require us to fill the unfilled whitespace at the end of the progress bar. However, if we add this ourselves and assign some extra CSS, then we can work some magic and make it look like the text colour is automatically changed to prevent clashing with the background.

Automatically changing text colour

For this example, I've used clip-path to restrict the visible areas of our elements and have preserved accessibility by moving the aria-label property to the progress container. Finally, I've used the aria-hidden attribute to prevent screen readers from seeing the text label multiple times.

<div class="progress progress-with-labels" aria-label="50% Example" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100">
    <div class="progress-foreground progress-bar" style="clip-path: inset(0 50% 0 0);" aria-hidden="true">50% Example</div>
    <div class="progress-background" style="clip-path: inset(0 0 0 50%);" aria-hidden="true">50% Example</div>
</div>
Enter fullscreen mode Exit fullscreen mode
.progress-with-labels {
    width: 100%;
    position: relative;

    .progress-foreground {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        color: white;
    }

    .progress-background {
        position: absolute;
        display: flex;
        justify-content: center;
        align-items: center;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        background: #e9ecef;
        color: black;
    }
}
Enter fullscreen mode Exit fullscreen mode

With this approach, we can achieve a final output looking similar to the below, with all of our text labels centred and easily readable.

Final example

Top comments (0)