添加这种炫酷效果的线性渐变和背景大小,任何机构都可以解释

时间:2017-07-27 00:19:40

标签: css linear-gradients background-position background-size

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

请看看,试着把我带出痛苦。 HTML CODE

<ul><li><a href="#" title="Home">Home</a></li> </ul>

css代码

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;}

如果有任何身体想要链接,这里也是链接。

https://codepen.io/arif_suhail_123/pen/jLPYOB

1 个答案:

答案 0 :(得分:1)

我在下面注释了你的风格,希望能够解释发生了什么。

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;}
}

背景位置

如果您查看background-position的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%。

这有帮助吗?