Home > Software design >  How to transition to hover and not:hover states with only one class
How to transition to hover and not:hover states with only one class

Time:06-10

I have two buttons to which I apply a simple 0.2s transition on the color change. Everything works perfectly but I would like to find an alternative way to write not: hover, so as to shorten the css.

Is there actually a way to tell all hover and not: hover states that they must have 0.2s of transition? So I won't have to write hover and not: hover for each class every time.

If possible, is there also a way to specify that it should only be applied to certain elements such as button ?

Sorry, but I'm new. I hope someone can show me the right way. I appreciate any response, thanks.

/*Download Button*/
a.downloadPdf {
   display: inline-flex;
   align-items: center;
   background: #C8E6C9;
   padding: 4px 15px;
   border-radius: 4px;
   font-size: 12px;
   font-weight: 500;
   color: #479C4B;
   box-shadow: rgb(0 0 0 / 15%) 0px 0px 6px -2px;
}

a.downloadPdf:hover {
   background: #43A047;
   color: #fff;
   box-shadow: rgb(0 0 0 / 15%) 0px 5px 10px 0px;
   transition: all 0.2s;
}

a.downloadPdf:not(:hover) {
   transition: all 0.2s;
}

/*Support Button*/
a.supportBtn {
   display: inline-flex;
   align-items: center;
   background: #FBE9E7;
   padding: 4px 15px;
   border-radius: 4px;
   font-size: 12px;
   font-weight: 500;
   color: #DF5242;
   box-shadow: rgb(0 0 0 / 15%) 0px 0px 6px -2px;
}

a.supportBtn:hover {
   background: #F4511E;
   color: #fff;
   box-shadow: rgb(0 0 0 / 15%) 0px 5px 10px 0px;
   transition: 0.2s; 
}

a.supportBtn:not(:hover) {
   transition: 0.2s; 
}
<a  href="#">Download PDF</a>
<a  href="#">Support</a>

CodePudding user response:

You don't need the :not at all, you can just put the transition on the base class so it transitions from hover state to the base state

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions

/*Download Button*/

a.downloadPdf {
  display: inline-flex;
  align-items: center;
  background: #C8E6C9;
  padding: 4px 15px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  color: #479C4B;
  box-shadow: rgb(0 0 0 / 15%) 0px 0px 6px -2px;
  transition: all 0.2s;
}

a.downloadPdf:hover {
  background: #43A047;
  color: #fff;
  box-shadow: rgb(0 0 0 / 15%) 0px 5px 10px 0px;
  transition: all 0.2s;
}


/*Support Button*/

a.supportBtn {
  display: inline-flex;
  align-items: center;
  background: #FBE9E7;
  padding: 4px 15px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  color: #DF5242;
  box-shadow: rgb(0 0 0 / 15%) 0px 0px 6px -2px;
  transition: all 0.2s;
}

a.supportBtn:hover {
  background: #F4511E;
  color: #fff;
  box-shadow: rgb(0 0 0 / 15%) 0px 5px 10px 0px;
  transition: all 0.2s;
}
<a  href="#">Download PDF</a>
<a  href="#">Support</a>

  • Related