gpt4 book ai didi

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

转载 作者:技术小花猫 更新时间:2023-10-29 10:34:32 25 4
gpt4 key购买 nike

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

示例:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com