Use the contrast-details Web Component to present colour contrast information of two colours. Check out this post I wrote for the zeroheight blog which gives more in depth explanation of the origins of this Web Component plus some more interesting usage examples.
contrast-details
The <contrast-details> component will accept two colour and in turn reveal their contrast ratio and grade level using the WCAG specification.
Features
This Web Component allows you to:
- Compare two colours and render their contrast details
- Render the contrast ratio
- Render the contrast level, as per WCAG specification
- Utilise CSS custom properties to provide values, either on the element or through inheritance, which also allows the element to use those colours as you wish
- Utilise a
levelattribute selector to style elements differently depending onaaa,aaandfailgrades
Usage
The <contrast-details> component can be used with the help of a script tag and adding two colours using CSS Custom Properties like so:
<script type="module" src="contrast-details.js"></script>
<contrast-details
style="--foreground: #444; --background: #ccc"
></contrast-details>A very reduced example of using contrast-details
Colours are supplied through --foreground and --background custom properties partly due to HTML attributes not being parsable in CSS, but mostly to give more flexibility to the user. With this approach colours can be set once and reused in both the component and in the CSS.
The component will also respect inheritance, meaning you can set colours on a parent element, in a style block or a CSS file to avoid repetition:
<script type="module" src="contrast-details.js"></script>
<div style="--foreground: #444">
<contrast-details style="--background: #ccc"></contrast-details>
<contrast-details style="--background: #ffffff"></contrast-details>
<contrast-details style="--background: #613fe8"></contrast-details>
</div>Example of using inheritance of the foreground colour on a parent element
You can also fully customise the presentation with CSS as well as HTML using a custom template:
<script type="module" src="contrast-details.js"></script>
<template id="contrast-details-template">
<p>
Contrast: <span data-key="ratio"></span> –
<span data-key="level"></span>
</p>
</template>
<contrast-details
style="--foreground: #444; --background: #ccc"
></contrast-details>More complex example of using contrast-details
Adding a <template> element to the page with an id of contrast-details-template will get picked up and used by all instance of contrast-details. Elements with data-key="ratio" and data-key="level" will be populated with ratio and level data respectively.
Demos
I've listed all the current running demos below if you want to see them in action:
Further reading
If you'd like try the Web Component for yourself or learn more about templating you can check out the documentation and further examples on GitHub: