微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

css – 悬停时从中心填充元素

如何创建按钮,以便在悬停时背景颜色从元素的中心向左和向右填充元素.

示例:

我知道如何使用CSS3过渡,并可以使其动画到所需的形状,但无法让它从中心向外过渡.

形状不会改变尺寸我只想用过渡来填充它.

解决方法

实现类似效果的另一种方法是使用线性渐变作为背景图像,将图像定位在元素的中心,然后在悬停时将背景大小从0%100%转换为100%100%.将X轴中的背景尺寸从0%增加到100%意味着背景颜色将慢慢填满元素并保持其位置固定在中心意味着颜色将从中心到左边缘和右边缘增长同时.

与web-tiki提供的答案相比,Gradients的支持度低于变换,这是一个缺点,但这种方法不需要任何额外的伪元素,这意味着它们可以用于其他目的.

div {
  position: relative;
  display: inline-block;
  padding: 15px 70px;
  border: 5px solid #B17461;
  color: #B17461;
  font-size: 30px;
  font-family: arial;
  background-image: linear-gradient(#B17461,#B17461);
  background-position: 50% 50%;
  background-repeat: no-repeat;
  background-size: 0% 100%;
  transition: background-size .5s,color .5s;
}
div:hover {
  background-size: 100% 100%;
  color: #fff;
}
<div>NEXT</div>

根据梯度图像的位置,可以使用相同的方法来产生各种不同的填充方法.

div {
  position: relative;
  display: inline-block;
  padding: 15px 70px;
  border: 5px solid #B17461;
  color: #B17461;
  font-size: 30px;
  font-family: arial;
  background-image: linear-gradient(#B17461,#B17461);
  background-repeat: no-repeat;
  transition: background-size .5s,color .5s;
}
.center-right-left,.center-top-bottom,.center-corner {
  background-position: 50% 50%;
}
.to-left {
  background-position: 100% 50%;
}
.to-right {
  background-position: 0% 50%;
}
.to-top {
  background-position: 50% 100%;
}
.to-bottom {
  background-position: 50% 0%;
}
.center-right-left,.to-left,.to-right {
  background-size: 0% 100%;
}
.center-top-bottom,.to-top,.to-bottom {
  background-size: 100% 0%;
}
.center-corner {
  background-size: 0% 0%;
}
div:hover {
  background-size: 100% 100%;
  color: #fff;
}
<h4>From center towards left and right</h4>
<div class='center-right-left'>NEXT</div>
<h4>From center towards top and bottom</h4>
<div class='center-top-bottom'>NEXT</div>
<h4>From center towards corners</h4>
<div class='center-corner'>NEXT</div>
<h4>From right to left</h4>
<div class='to-left'>NEXT</div>
<h4>From left to right</h4>
<div class='to-right'>NEXT</div>
<h4>From bottom to top</h4>
<div class='to-top'>NEXT</div>
<h4>From top to bottom</h4>
<div class='to-bottom'>NEXT</div>

原文地址:https://www.jb51.cc/css/215812.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。