<div class="demo-container">
<h2>Dynamic Color Spectrum</h2>
<p>The <code>background-color</code> is set with <code>oklch()</code>, where the hue is calculated based on the item's index and the total sibling count.</p>
<div class="controls">
<button id="add-item">Add Color</button>
<button id="remove-item">Remove Color</button>
</div>
<div class="spectrum-list">
<div class="spectrum-item"></div>
<div class="spectrum-item"></div>
<div class="spectrum-item"></div>
<div class="spectrum-item"></div>
<div class="spectrum-item"></div>
</div>
</div>
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&display=swap");
.spectrum-list {
display: flex;
height: 80px;
background: #34495e;
border-radius: 10px;
padding: 1rem;
gap: 1rem;
}
.spectrum-item {
--start-hue: 180; /* Teal */
--hue-range: 120; /* Range from Teal to Magenta */
flex-grow: 1;
border-radius: 6px;
/* distribute a range of hues across all items using sibling-count and index */
background-color: oklch(
65% 0.35
calc(
var(--start-hue) + (var(--hue-range) / (sibling-count() - 1)) *
(sibling-index() - 1)
)
);
transition: background-color 0.4s ease;
}
@layer basestyles {
:root {
--bg-color: #f0f2f5;
--text-color: #333;
--accent-grad: linear-gradient(160deg, #ff7e9b, #8a7eff);
}
body {
font-family: "Poppins", sans-serif;
background-color: var(--bg-color);
color: var(--text-color);
margin: 0;
padding: 3rem 1rem;
display: grid;
gap: 3.5rem;
justify-items: center;
}
.demo-container {
width: 100%;
max-width: 650px;
text-align: center;
}
h2 {
margin-bottom: 0.5rem;
}
p {
margin-top: 0;
margin-bottom: 1.5rem;
color: #666;
max-width: 500px;
margin-left: auto;
margin-right: auto;
}
code {
background-color: #e2e5e9;
padding: 0.2em 0.4em;
border-radius: 4px;
font-size: 0.9em;
}
button {
font-family: inherit;
font-size: 1rem;
font-weight: 600;
padding: 0.75rem 1.5rem;
border: none;
border-radius: 8px;
background-image: var(--accent-grad);
color: white;
cursor: pointer;
transition: transform 0.2s ease, box-shadow 0.2s ease;
margin: 0 0.5rem 1.5rem;
&:hover {
transform: translateY(-2px);
box-shadow: 0 6px B20px rgba(138, 126, 255, 0.4);
}
}
}
const spectrumList = document.querySelector(".spectrum-list");
const addItemBtn = document.getElementById("add-item");
const removeItemBtn = document.getElementById("remove-item");
addItemBtn.addEventListener("click", () => {
if (spectrumList.children.length < 12) {
const newItem = document.createElement("div");
newItem.classList.add("spectrum-item");
spectrumList.appendChild(newItem);
}
});
removeItemBtn.addEventListener("click", () => {
if (spectrumList.children.length > 2) {
spectrumList.removeChild(spectrumList.lastElementChild);
}
});
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.