Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more efficient way to make background position change from left to right on hover?

Tags:

html

css

This is the code I currently have to make it seem as though the left border expands on hover, even though it's just the background changing. Is there a more efficient way to write this code?

edit: Efficient meaning a better way to write it.

span {
  padding: 5px;
  text-align: center;
  border-left: 5px solid black;
  background: linear-gradient(to left, yellow 50%, black 50%);
  background-size: 200%, 100%;
  background-position: right;
  transition: .5s ease;
}

span:hover {
  background-position: left;
  color: white;
}
<span>This is some example text.</span>
like image 947
Joey Knight Avatar asked Dec 08 '25 09:12

Joey Knight


1 Answers

I prefer using pseudo elements for this stuff, as you can then add transforms and such to the pseudo element for better performance.

Only problem with this is that you need to wrap your span in another element, so that you can position the text over the pseudo element with z-index. Otherwise it will just cover your text.

span {
  color: black;
  transition: color .5s ease;
  z-index: 2;
  position: relative;
}

p {
  padding: 5px;
  text-align: center;
  border-left: 5px solid black;
  background-color: yellow;
  position: relative;
  overflow: hidden;
  display: inline-block;
}

p::after {
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background-color: black;
  transition: transform .5s ease;
  transform: translateX(-100%);
  will-change: transform;
  z-index: 1;
}

p:hover::after {
  transform: translateX(0);
}

p:hover span {
  color: white;
}
<p><span>This is some example text.</span></p>
like image 145
popshuvit Avatar answered Dec 10 '25 23:12

popshuvit