线性渐变和背景大小增加了这种很酷的效果,任何body都可以解释



如果这是一个愚蠢的问题,我很抱歉,但是这段代码让我发疯,我把它剥离下来,以为我能够理解,但是在这样做并投入了 2-4 个小时之后,现在我对我认为我知道的事情感到困惑。 下面的代码在我结束的时候添加了这种很酷的效果,似乎背景从底部出现并转到顶部, 只认为我知道它与背景图像、线性渐变、背景大小和背景位置有关

请看一看,试着把我从痛苦中解救出来。

li {
background-image: linear-gradient(to bottom, transparent 50%, #a2d39c 50%, #a2d39c 95%, #7cc576 95%);
background-size: 100% 200%;
transition: all .25s ease;
}
li:hover {
background-position: bottom center;
}
li a {
display: block;
padding: 1rem 0;
}
<ul>
<li><a href="#" title="Home">Home</a></li>
</ul>

我在下面注释了您的样式,希望能解释正在发生的事情。

li {
// You're creating a background gradient, where the first 50% is transparent, the next 45% is #a2d39c and the last 5% is #7cc576
background-image: 
linear-gradient(to bottom, 
transparent 50%, 
#a2d39c 50%, #a2d39c 95%, #7cc576 95%);
// The background size is twice the height of your element. Therefore with the 50% transparency and initial position, you're not going to see anything
background-size: 100% 200%;
// This will nicely transition between CSS property values when they change
transition: all .25s ease;
}
li:hover {
// When you hover over your list item, you're changing the position so that the bottom of the background is visible. This causes the 50% transparent portion of the background to disappear, and the coloured portion to slide into view
background-position: bottom center;}
}

背景位置

如果你查看背景位置的CSS规范,你会看到默认值是0% 0%,基本上是top left

您的 CSS 代码未指定初始背景位置,因此它将默认为top left。请记住这一点。

您的背景渐变是to bottom定义的,因此从top -> bottom.前 50% 是transparent(不可见(。第二个50%由两种不同的颜色组成。

然后考虑背景渐变是元素高度的两倍。这由background-size: 100% 200%指定(100% 宽度,200% 高度(。背景可以大于应用它的元素,并且任何溢出都将被隐藏。

所以最初当你只显示背景渐变的上半部分时,你会看到什么?只有transparent部分。

然后,当您在悬停时覆盖background-position时,您说现在显示bottom center部分。看到背景如何与元素的整个宽度相匹配,center水平值不会改变任何内容。但bottom垂直设置确实如此。现在意味着显示第二个 50%。

这有帮助吗?

最新更新