Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

html - CSS animate custom properties/variables

I have been trying to get this to work for a while.

The point is that the inner div will have some shape and there will probably more than one (That's why I used the nth-child selector). This inner div is supposed to be shown and then be hidden again both for some set amount of time. the problem is, that I would like to animate all the (later) multiple inner divs in one animation. For this I thought I could use CSS variables, but this does not seem to work.

What I am trying to archieve in this example is the inner div basically just blinking by using the variable. But my result in Firefox is just a black box.

Am I missing anything? I already looked up if one could even use CSS variables in @keyframes and sure enough you can. The only problem with them in animations seems to be that they are not interpolated in between but that they suddenly switch which is not a problem in this case.

@keyframes test{
    from{
        --one: 0;
    }
    to{
        --one: 1;
    }
}

#test{
    width: 100px;
    height: 200px;
    background-color: black;
    animation: test 1s infinite;
}
#test :nth-child(1){
    width: 20px;
    height: 20px;
    margin: auto;
    background-color: white;
    opacity: var(--one,0);
}
<div id="test">
    <div></div>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This can be achieved by defining variables using (as of writing this, not well-supported) @property, which allows declaring types and that allows the browser to "understand", for example, that a certain property (variable) is a Number and then it can gradually animate/transition that variable.

Example Code:

@property --opacity {
  syntax: '<number>'; /* <- defined as type number for the transition to work */
  initial-value: 0;
  inherits: false;
}

@keyframes fadeIn {
  50% {--opacity: 1}
}

html {
  animation: 2s fadeIn infinite;
  background: rgba(0 0 0 / var(--opacity));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...