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

问题描述 投票:0回答:1

我想知道如何让一个对象从中间变宽,而不是从左边变宽,这是我的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%;
}

悬停时,对象不是从中间变宽,而是从左边变宽。我试过在CSS中的a:hover::before中加入transform: translate(-50%, 0);,它有点工作,但它使它有点摇晃(我不知道如何解释)。谁能帮忙解决这个问题?

html css width transition
1个回答
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>

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,点击 此处.


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{}上如你所愿,这种格式我发现不会有晃动。

© www.soinside.com 2019 - 2024. All rights reserved.