<color-swatch>
Examples
Basic usage
Normal size | Large | |
---|---|---|
Static |
|
|
Editable |
|
|
With slot content
Before and after:
<color-swatch>
<label slot="before" for=c1>Accent color:</label>
<input value="oklch(70% 0.25 138)" id=c1 />
</color-swatch>
<color-swatch size="large">
<label slot="before" id=c2>Accent color:</label>
<input value="oklch(70% 0.25 138)" id=c2 />
<small slot="after">Tip: Pick a bright medium color.</small>
</color-swatch>
Adding text within the default swatch:
<color-swatch size="large">
<div slot="swatch-content">Some text</div>
<input value="oklch(70% 0.25 138)" id=c1 />
</color-swatch>
Note that the text color will automatically switch from black to white to remain readable (using this technique).
Replacing the whole swatch with a custom element:
<color-swatch size="large">
<div slot="swatch">Some text</div>
<input value="oklch(70% 0.25 138)" id=c1 />
</color-swatch>
Bound to CSS property
You can automatically bind the color swatch to a CSS property by setting the property
attribute.
Then you don’t need to provide an initial value, it will be read from the CSS property,
and updating the color will update the CSS property.
<color-swatch size="large" property="--color-red">
<input />
</color-swatch>
You can use scope
to select the closest ancestor (via a CSS selector) on which the CSS property will be read from and written to.
If you don’t, the <html>
element will be used.
Events
<color-swatch size="large" oncolorchange="this.nextElementSibling.textContent = this.color">
<input value="oklch(70% 0.25 138)" />
</color-swatch>
<color-inline></color-inline>
Update via JS
Static
<color-swatch id="dynamic_static">oklch(70% 0.25 138)</color-swatch>
<button onclick='dynamic_static.color = "oklch(60% 0.15 0)"'>Change color</button>
Editable
<color-swatch id="dynamic_editable">
<input value="oklch(70% 0.25 138)" />
</color-swatch>
<button onclick='dynamic_editable.color = "oklch(60% 0.15 0)"'>Change color</button>
Installation
To install all color elements, check out the instructions on the homepage.
The rest of this section is about using only <color-swatch>
.
The quick and dirty way is straight from the CDN (kindly provided by Netlify):
<script src="https://elements.colorjs.io/src/color-swatch/color-swatch.js" type="module"></script>
or in JS:
import "https://elements.colorjs.io/src/color-swatch/color-swatch.js";
If you are using npm to manage your dependencies, you can import it via:
import "color-elements/color-swatch";
or:
import { ColorSwatch } from "color-elements";