[CSS] Tip: CSS variable usage

Sometime the element width is dynmiac, and you want to use the width in css, how to do that

1. Define css variable in css file, --wis the container's width

@keyframe move {
    50% {
        transform: translateX(calc(var(--w) - 100%))
    }
}

2. Bridge with JS

const container = document.querySelector('.container')
const w = container.offsetWidth
container.style.setProperty('--w', w + 'px')

Then the --wis available in CSS as well

 

The same way is done in Vue v-bind

 

posted @ 2025-05-06 14:17  Zhentiw  阅读(4)  评论(0)    收藏  举报