4

我在尝试使用多个背景时遇到了一个奇怪的问题。我想要的基本效果是边缘的渐变背景和中间的透明背景。这是真正的基本代码:

background: transparent, linear-gradient(45deg, #f06, yellow);
background-size:50% 50%, 100% 100%;
background-position: 50% 50%, 0 0;
background-repeat: no-repeat;

我正在使用dabblet来玩弄它。如果我使用该代码,我将一无所获(我替换transparentgreen确保我能够看到它):http ://dabblet.com/gist/5339331

但是,如果我反转背景(backgound: linear-gradient(45deg, #f06, yellow), green;),它会按预期完美工作,当然它是相反的:http : //dabblet.com/gist/5339291

这里发生了什么?为什么它会以一种方式工作而不是另一种?我还尝试将渐变替换blue为使其变得简单,但它不起作用:http ://dabblet.com/gist/5339396

仅供参考,我正在 Chrome 27 中进行测试,并收到黄色!警告Invalid property value.

编辑:这是我想要的效果的更好(但仍然损坏)示例。在这个例子中,有四块,每块都有自己的渐变背景。理想情况下,我会拥有一件,因为

  1. 它将允许看起来正确的渐变。

  2. 这看起来很可怕,并且在移动设备上播放效果不佳。

  3. 如果可能的话,最好避免额外的固定/绝对 div

4

2 回答 2

2

您可能知道,transparent是颜色值而不是图像值,就像blue. 因为它是一个颜色值,所以它必须在background简写中最后指定,并且只有在那里,因为只有基础层可能有背景颜色。这就是 Chrome 的 Web Inspector 报告您拥有的无效属性值的原因。

不幸的是,没有一种方法可以使用多个背景来指定单个背景图像及其被切掉的区域(例如,在中间部分显示一个透明开口)。

不过,您在 jsFiddle 上所拥有的只是一个步骤。div您可以通过向两者添加::before::after伪元素来轻松地完全取消额外的元素htmlbody相反,您有四个伪元素可以使用。您还需要适当地使用background-sizebackground-position调整渐变背景,使它们看起来无缝。

由于您希望渐变在保持无缝的同时保持半透明,因此您需要防止它们重叠。这很容易通过调整偏移量来实现background-size

这是我使用的 CSS:

html::before, html::after, body::before, body::after {
    display: block;
    position: fixed;
    background: linear-gradient(45deg, rgba(255, 0, 0, 0.5), rgba(0, 255, 0, 0.5));
    content: '';
}

html::before, html::after {
    height: 25%;
    left: 25%;
    right: 25%;
    background-size: 200% 400%;
}

body::before, body::after {
    width: 25%;
    top: 0;
    bottom: 0;
    background-size: 400% 100%;
}

html::before { top:    0; background-position: top;    }
html::after  { bottom: 0; background-position: bottom; }
body::before { left:   0; background-position: left;   }
body::after  { right:  0; background-position: right;  }

jsFiddle 预览带有边框以显示我如何排列伪元素

你不能只用一个盒子来做到这一点,所以是的,它在移动设备上可能表现不佳。如果这不能很好地工作,那么您可以使用 SVG 背景来实现这一点,或者如果失败,您可能不得不回退到使用传统的预渲染背景图像。

于 2013-04-09T07:07:59.293 回答
0

CSSbackground速记属性语法如下:

background: background-color background-image background-repeat background-attachment, background-position

请注意,没有任何逗号,因此最好不要使用它们,尤其是在分隔background-colorand时background-image

使用所有这些并回到原始示例:http ://dabblet.com/gist/5340042

于 2013-04-08T20:08:23.727 回答