CSS悬停过渡,从中心开始的宽度

时间:2020-06-09 14:46:06

标签: html css width transition

我想知道如何使一个对象从中心而不是从左侧变宽。 这是我的HTML:

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

这是我的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%;
}

它不是在悬停时从中心变宽,而是从左侧变宽。我尝试添加转换:translate(-50%,0);到a:hover ::: css之前的版本,虽然有点奏效,但是却有点不稳定(我不知道如何解释)。有人可以帮忙吗?

3 个答案:

答案 0 :(得分:2)

您只能在有背景的情况下这样做:

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>

答案 1 :(得分:0)

我想我解决了。我向元素添加了::after,旋转了渐变,并使::after向左50%,而::before向右50%。像这样:

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;
  border: none;
  outline: none;
  background-image: linear-gradient(45deg, #eea949, #ff3984);
  transition: .5s;
}

a::after {
  content: '';
  position: absolute;
  height: 100%;
  width: 0%;
  top: 0;
  right: 50%;
  z-index: -1;
  background-image: linear-gradient(135deg, #ff3984, #eea949);
  border: none;
  outline: none;
  transition: .5s;
}

a:hover::before {
  width: 50%;
}

a:hover::after {
  width: 50%;
}
<html>

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

</html>

我希望这会有所帮助。如果要查看JSFiddle,请单击here

答案 2 :(得分:0)

将这些样式添加到body元素以使链接居中。然后从链接中删除position: absolute; top: 0 and left:0;(对于flex来说它们是多余的),并添加此样式以使其成为父项。

body{
    display: flex;
    justify-content: center;
    align-items: center;
} 
a{ 
    position: relative
    transition: all .1s;
}

,然后根据需要将transform: translateX(-50%);添加到a​​:hover :: before {}上。 我发现这种格式没有摆动。