Search code examples
htmlcsswidthtransition

CSS hover transition, width from the center


I was wondering how I would make an object wider from the center, instead of from the left. Here is my HTML:

<html>
  <body>
    <a href='#'>Hover</a>
  </body>
</html>

and here is my CSS:

body{
  margin:0;
  padding:0;
  background-color:#262626;
}
a{
  position:absolute;
  top:50%;
  left:50%;
  transform:translate(-50%,-50%);
  padding:10px 25px;
  border:2px solid white;
  text-decoration:none;
  color:white;
  font-family:verdana;
  font-size:27px;
  text-transform:uppercase;
  letter-spacing:4px;
  transform:1s;
}
a::before{
  content:'';
  position:absolute;
  height:100%;
  width:0%;
  top:0;
  left:50%;
  z-index:-1;
  background-image:linear-gradient(45deg, #eea949,#ff3984);
  transition:.5s;
}
a:hover::before{
  width:100%;
}

instead of widening from the center on hover, it widens from the left. I have tried adding transform: translate(-50%, 0); to the a:hover::before in the css, it kind of worked, but it made it a little wobbly (I don't know how to explain it). Can someone help with this?


Solution

  • You can do it with only background:

    body {
      margin: 0;
      padding: 0;
      background-color: #262626;
    }
    
    a {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      padding: 10px 25px;
      border: 2px solid white;
      text-decoration: none;
      color: white;
      font-family: verdana;
      font-size: 27px;
      text-transform: uppercase;
      letter-spacing: 4px;
      transition: 0.5s;
      background: linear-gradient(45deg, #eea949, #ff3984) center/0% 100% no-repeat;
    }
    
    a:hover {
      background-size: 100% 100%;
    }
    <a href='#'>Hover</a>