JSFiddle - React, Tailwind, and code Playground
Using css variables to alter color based on mouse position.
by Travis Almand
November 10, 2016
HTML
<p>Moving mouse left/right changes hue, up/down changes saturation. Based on mouse position within window height/width.</p>
<p>This is the color range you should be seeing from left to right.</p>
<div id="color_range"></div>
<div id="box">
<h3>dynamic colors</h3>
</div>
CSS
:root {
--hue: 0;
--sat: 100%;
--hsl: hsl(var(--hue), var(--sat), 50%);
}
#color_range {
background: linear-gradient(to right, hsl(0,100%,50%), hsl(60,100%, 50%), hsl(120,100%, 50%), hsl(180, 100%, 50%), hsl(240,100%,50%), hsl(300,100%,50%), hsl(360, 100%, 50%) 100%);
height: 20px;
margin: 20px auto;
width: 90%;
}
#box {
border: 4px solid var(--hsl);
color: var(--hsl);
height: 100px;
margin: 20px auto;
text-align: center;
width: 100px;
}
JavaScript
document.addEventListener('mousemove', (e) => {
var widthPercent = e.clientX / document.documentElement.clientWidth;
var heightPercent = 100 - ((e.clientY / document.documentElement.clientHeight) * 100);
var hue = Math.round(360 * widthPercent);
document.documentElement.style.setProperty('--hue', hue);
document.documentElement.style.setProperty('--sat', heightPercent + '%');
})