CSS contrast-color()

CSS 대비 색상 함수

The browser chooses black or white text for stronger contrast against a background.

···
html
<div class="v"><header>CONTRAST COLOR <span id="hex">#e8cb66</span></header><div class="stage contrast"><div class="swatch" id="swatch">Readable label</div><div class="choices"><span id="darkChoice">black</span><span id="lightChoice">white</span></div></div><div class="muted">background → higher contrast text</div></div>
css
.v{width:min(94vw,760px);height:min(88vh,320px);padding:clamp(9px,2.4vmin,18px);border:1px solid var(--line);border-radius:12px;background:var(--surface);font:500 clamp(12px,2.4vmin,16px)/1.3 var(--font-sans,system-ui,sans-serif);display:flex;flex-direction:column;gap:clamp(5px,1.4vmin,10px);overflow:hidden}.v header{display:flex;align-items:center;justify-content:space-between;gap:8px;color:var(--accent);font-weight:700}.v header span{color:var(--muted);font-weight:500}.v .stage{flex:1;min-height:0;position:relative}.v .muted{color:var(--muted)}.v .active{background:color-mix(in srgb,var(--accent) 18%,var(--surface));border-color:var(--accent)!important;color:var(--fg)}.v button{font:inherit;color:var(--fg);background:var(--bg);border:1px solid var(--line);border-radius:7px;padding:5px 8px;cursor:pointer}.contrast{display:flex;align-items:center;justify-content:center;gap:12px}.swatch{width:55%;height:65%;display:grid;place-items:center;border-radius:9px;background:#e8cb66;color:contrast-color(#e8cb66);border:1px solid var(--line);font-weight:700;transition:background .5s,color .5s}.choices{display:flex;flex-direction:column;gap:8px}.choices span{padding:6px;border:1px solid var(--line);border-radius:6px}.choices span.on{border-color:var(--accent);color:var(--accent)}
js
let dark=false;function tick(){dark=!dark;const hex=dark?"#243655":"#e8cb66",s=document.getElementById("swatch");s.style.background=hex;s.style.color="contrast-color("+hex+")";if(!CSS.supports("color","contrast-color("+hex+")"))s.style.color=dark?"white":"black";document.getElementById("hex").textContent=hex;document.getElementById("darkChoice").classList.toggle("on",!dark);document.getElementById("lightChoice").classList.toggle("on",dark)}tick();setInterval(tick,1100)

`contrast-color()` returns whichever of black or white has stronger contrast with a given background. It reduces manual color pairing for components with variable backgrounds.

The demo alternates light and dark swatches so the text color changes. It does not choose arbitrary brand colors or replace accessibility checks for a full page.

When to use

Use it for short labels on user-selected background colors.

Open as page ↗