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

标签 css button css-transitions css-shapes

如何创建一个按钮,以便悬停时背景颜色从元素的中心填充到元素的左侧和右侧。

示例:

Button filled by background color on hover

我知道如何使用 CSS3 transitions 并可以将其动画化为所需的形状,但无法将其从中心向外过渡。

形状不会改变大小,我只想使用 transition 填充它。

最佳答案

另一种实现类似效果的方法是使用 linear-gradient 作为 background-image,将图像定位在元素的中心,然后过渡 background-size0% 100%100% 100% 悬停。将 X 轴上的 background-size0% 增加到 100% 意味着背景颜色将慢慢填充元素并保持其位置fixed at the center 意味着颜色会同时从中心向左边缘和右边缘增长。

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

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>

关于css - 悬停时从中心填充元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23934749/

相关文章:

android - 如何检测虚拟按钮(Android 4)?

使用封面时的 CSS3 淡入淡出背景图像

javascript - 使用带有 PostCSS 的 React 的 className 属性有条件地在三元组中添加多个类

jquery - 使用 Jquery 创建下拉菜单(显示/隐藏元素)

ios - 让 UIImageView 充当 Facebook 登录按钮

jquery - 按钮禁用效果在第一次单击后不起作用

HTML 标签正确对齐,但似乎仍然乱七八糟

javascript - 二维网格知道正方形是否在范围内

html - CSS Transition 没有相应地工作

javascript - 如果不查询宽度属性,过渡就不起作用