0

I have some tiles that have an ordinary background-color and show a CSS gradient on hover, and I want to add a transition between these. I've seen this solution, but as far as I can tell the only way to make it work for background colours is to treat it as a gradient by adding two duplicate initial colours and transitioning those:

@property --myColor1 {
  syntax: '<color>';
  initial-value: #e6e6e6;
  inherits: false;
}

@property --myColor2 {
  syntax: '<color>';
  initial-value: #e6e6e6;
  inherits: false;
}

This seems redundant and it feels like there should be a cleaner way to do this. Is there?

2 Answers 2

2

You can fade the opacity of the upper layer which is a one-color gradient:

@property --o {
  syntax: '<number>';
  initial-value: 1;
  inherits: false;
}

.box {
  --c: purple; /* the color */
  
  background:
   conic-gradient(rgb(from var(--c) r g b/var(--o)) 0 0),
   linear-gradient(red,blue); /* the gradient */
  transition: --o .5s;
  height: 200px;
}
.box:hover {
  --o: 0;
}
<div class="box"></div>

Another syntax:

@property --o {
  syntax: '<number>';
  initial-value: 1;
  inherits: false;
}

.box {
  --c: purple; /* the color */
  
  border-image: conic-gradient(rgb(from var(--c) r g b/var(--o)) 0 0) fill 0;
  background: linear-gradient(red,blue);
  transition: --o .5s;
  height: 200px;
}
.box:hover {
  --o: 0;
}
<div class="box"></div>

Sign up to request clarification or add additional context in comments.

1 Comment

I had to move most properties to the hover state to make the first method work for me, but other than that this works beautifully, and without any extra markup. TIL about one-colour gradients. Thank you!
1

Use pseudo element:

* {
  margin: 0;
}

.card {
  padding: 40px;
  background-color: #eee;
  position: relative;
  display: inline-flex;
  flex-direction: column;
  gap: 8px;
  text-align: center;
  &>* {
    position: relative;
    z-index: 1;
  }
  &:before{
    content: '';
    position: absolute;
    inset: 0;
    background: linear-gradient(40deg, rgba(226, 66, 249, 0.94) 40%, rgb(0, 153, 255) 80%);
    opacity: 0;
    transition: opacity .4s;
  }
  &:hover {
    &:before {
      opacity: 1;
    }
  }
}
<div class="card">
  <h3 class="card-title">Lorem ipsum.</h3>
  <div class="card-desc">Lorem ipsum.</div>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.