Css按钮渐变背景位置

时间:2018-02-16 06:52:17

标签: html css background-position

我使用了一个具有背景效果的按钮。但是,我不明白背景位置是如何工作的。

背景位置设置为右侧,然后当鼠标悬停在按钮上时,背景向左移动。但是,我无法弄清楚为什么“蓝色”似乎是从左到右,就像背景向右移动一样。

背景不应该向左移动吗?

button {
  color: white;
  background: linear-gradient(to left, red 50%, blue 50%);
  background-size: 200%;
  background-position: right bottom;
  border: none;
  border-radius: unset;
  width: 85px;
  height: 35px;
  transition: 2s ease;
  cursor: pointer;
}

button:hover {
  background-position: left bottom;
}
<button>Button</button>

Fiddle Link

2 个答案:

答案 0 :(得分:0)

从您的按钮中移除background-position或更改backgrond-position:left bottom之类的订单,并在您的渐变和悬停位置应用right代替left,如下所示。

button
{
color:white;
background: linear-gradient(to right, red 50%, blue 50%);
background-size: 200%;
border: none;
border-radius: unset;
width: 85px;
height: 35px;
transition: 2s ease;
cursor: pointer;
}
button:hover
{
background-position:right bottom;
}

我在以下代码段中添加了相同内容。

button
{
	color:white;
	background: linear-gradient(to right, red 50%, blue 50%);
	background-size: 200%;
	border: none;
    border-radius: unset;
    width: 85px;
    height: 35px;
	transition: 2s ease;
	cursor: pointer;
}
button:hover
{
	background-position:right bottom;
}
<button>
Button
</button>

答案 1 :(得分:0)

逻辑很简单,让我们从每个属性开始。

首先你定义了像int*这样的渐变,这意味着从左边开始,我们将得到50%的红色,然后是50%的蓝色:

&#13;
&#13;
linear-gradient(to left, red 50%, blue 50%)
&#13;
div {
  height:50px;
  width:100px;
  background-image:linear-gradient(to left, red 50%, blue 50%)
}
&#13;
&#13;
&#13;

现在您指定背景大小为200%,这意味着您将背景的大小缩放2.要说明检查以下代码以查看初始背景和缩放背景:

&#13;
&#13;
<div>
</div>
&#13;
div {
  height:50px;
  width:100px;
  background-image:linear-gradient(to left, red 50%, blue 50%)
}
div:nth-child(2) {
  height:100px;
  width:200px;
  margin-top:20px;
}
&#13;
&#13;
&#13;

但是背景应该始终符合元素的大小,在这种情况下,你只能看到它的1/4(因为我们在两个方向都做了一个缩放)。 <div> </div> <div> </div>将决定这一点。当您将其设置为右下角时,您可以使背景的右下角与元素的右下角相匹配,如下所示:

enter image description here

所以你会看到黄色部分。如果您指定左下角,您将拥有:

enter image description here

所以它就像黄色框从右到左滑动 或黄色框固定,背景从从左向右移动(这个你看到的行为,因为这里的黄色框是你的按钮)。

此次移动的主要原因是溢出,因此要改变其位置,背景应朝相反方向移动,这与背景大小小于100%不同。如果背景大小为100%,您将看不到任何移动,因为两个位置都相同!

以下是3个不同案例的工作示例:

&#13;
&#13;
background-position
&#13;
div {
  height:50px;
  width:100px;
  background-image:linear-gradient(to left, red 50%, blue 50%);
  border:1px solid;
  background-position:right bottom;
  background-repeat:no-repeat;
  transition:1s;
}
.d1 {
  background-size:50%;
}
.d2 {
  background-size:100%;
}
.d3 {
  background-size:200%;
}

body:hover div{
  background-position:left bottom;
}
&#13;
&#13;
&#13;

相关问题