Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
CSS-Tricks
Search

Updating a CSS Variable with JavaScript

Chris Coyier on

Get affordable and hassle-free WordPress hosting plans with Cloudways —start your free trial today.

Here’s a CSS variable (formally called a “CSS custom property“):

:root {  --mouse-x: 0px;  --mouse-y: 0px;}

Perhaps you use them to set a position:

.mover {  left: var(--mouse-x);  top: var(--mouse-y);}

To update those values from JavaScript, you’d:

let root = document.documentElement;root.addEventListener("mousemove", e => {  root.style.setProperty('--mouse-x', e.clientX + "px");  root.style.setProperty('--mouse-y', e.clientY + "px");});

That’s all.

See the PenSet CSS Variable with JavaScript by Chris Coyier (@chriscoyier) onCodePen.

Psst! Create a DigitalOcean account and get$200 in free credit for cloud-based hosting and services.

Comments

  1. malipetek
    Permalink to comment#

    You got to be kidding, this is like JS/CSS wedding.

  2. Matt Wood
    Permalink to comment#

    Relevant, use React to stagger animations with a CSS variable:

    https://twitter.com/DavidKPiano/status/1009499115720495114

  3. Edson
    Permalink to comment#

    I’d add* { cursor: none; } for demo purpose.

  4. Arnaud
    Permalink to comment#

    Is it more powerful than setting directly thetop andleft style of an element ?

    • Anders Grimsrud
      Permalink to comment#

      I see at least two advantages. One is the CSS readability: If you want to pin an element to the position of your cursor,left: var(--mouse-x) just makes total sense to me. And if there are more than one element reacting to the movement of your mouse, you don’t have to update them one by one in your JS – you simply update the CSS variable once. Mixed with a few other CSS techniques this pretty much opens up for a whole lot of new opportunities. I just played around with this to make somecustom scrollbars and I’m sure there are plenty of other use cases! :-)

    • Arnaud`
      Permalink to comment#

      Yeas, I already use these powers evry day actually ! So great… until your client asks for IE compatibility. Anyway, I just decided to drop all IE projects, because I really like CSS variables really much !
      My question was more about performance : is it more performant to set a CSS variable than setting thetop andleft styles directly ?

This comment thread is closed. If you have important information to share, pleasecontact us.

[8]ページ先頭

©2009-2025 Movatter.jp