Felipe Wagner
Felipe Wagner

Reputation: 148

CSS Animation Preserve Original Properties

I have this CSS Animation that starts with a background-color and has a transition to the original background-color:

@high-light-white: #ffffff;
@high-light-yellow: #ede5d0;
@high-light-default: #dce1ea;
@high-light-duration: 10s;

.highlight-comment {
    -webkit-animation-name: highlight; /* Safari 4.0 - 8.0 */
    -webkit-animation-duration: @high-light-duration; /* Safari 4.0 - 8.0 */
    animation-name: highlight;
    animation-duration: @high-light-duration;
}
@keyframes highlight {
    from {
        background-color: @high-light-yellow;
    }
    to {
        background-color: @high-light-default;
    }
}

My problem is that I have another element that I want to use this same CSS, but it has a different background-color. Is there a way I can animate it so the transition is set to the original background-color without specifying it?

Upvotes: 2

Views: 72

Answers (3)

Temani Afif
Temani Afif

Reputation: 272901

An idea is to specify only one color in the animation and make it from 0% to x% then the remaining will be the default one:

.box {
  height: 150px;
  background: red;
  animation: anim 2s linear infinite;
}

.box-2 {
  height: 50px;
  background: black;
  animation: anim 2s linear infinite;
}

@keyframes anim {
  0%,
  20% {
    background: blue;
  }
}
<div class="box">

</div>
<div class="box-2">

</div>

Upvotes: 2

Tobias
Tobias

Reputation: 248

Try

.div-with-original-background-color {
    background-color: blue;
}
.div-with-another-original-background-color {
    background-color: green;
}

@keyframes highlight {
    from {
        background-color: @high-light-yellow;
    }
    to {
        background-color: transparent;
    }
}

<div class="div-with-original-background-color">
    <div class="highlight-comment">
       Some Sweet comment...
    </div>
</div>

<div class="div-with-another-original-background-color">
    <div class="highlight-comment">
       foo
    </div>
</div>

Upvotes: -1

Paulie_D
Paulie_D

Reputation: 115047

CSS Variables / Custom properties can do that.

The same animation, with the same variables, but the variable is complied at runtime and can be changed on single element by re-stating it.

:root {
  --default: blue;
  --highlight: lightyellow;
}

div {
  width: 50%;
  margin: 1em auto;
  border: 1px solid grey;
  height: 50px;
}

.one,
.two {
  background: var(--default);
  animation: highlight 2.5s linear infinite;
}

.two {
  --default: red;
}

@keyframes highlight {
  from {
    background-color: var(--highlight);
  }
  to {
    background-color: var(--default);
  }
}
<div class="one"></div>

<div class="two"></div>

Upvotes: 1

Related Questions