我在尝试使用多个背景时遇到了一个奇怪的问题。我想要的基本效果是边缘的渐变背景和中间的透明背景。这是真正的基本代码:
background: transparent, linear-gradient(45deg, #f06, yellow);
background-size:50% 50%, 100% 100%;
background-position: 50% 50%, 0 0;
background-repeat: no-repeat;
我正在使用 dabblet玩弄它。如果我使用该代码,我将一无所获(我将 transparent
替换为 green
,确保我能够看到它):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.
编辑:这是一个better (yet still broken) example我想要的效果。在这个例子中,有四 block ,每 block 都有自己的渐变背景。理想情况下我会拥有一件因为
它将允许看起来正确的渐变。
这看起来很糟糕,而且在移动设备上播放效果不佳。
如果可能,最好避免额外的固定/绝对 div
最佳答案
您可能知道,transparent
是颜色值而不是图像值,就像 blue
一样。因为它是一个颜色值,所以必须在 background
速记的最后指定,并且仅在那里,因为 only the base layer may have a background color .这就是 Chrome 的 Web 检查器报告您拥有的属性值无效的原因。
遗憾的是,没有一种方法可以使用多个背景来指定单个背景图像及其被剪切的区域(例如,在中间部分显示一个透明开口)。
不过,您在 jsFiddle 上拥有的是一个步骤。您可以通过将 ::before
和 ::after
伪元素添加到 html 来轻松地完全消除额外的
和 div
元素body
代替,所以你有四个伪元素可以使用。您还需要使用 background-size
和 background-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 preview ( with borders to show how I've arranged the pseudo-elements )
仅用一个盒子无法做到这一点,所以是的,它在移动设备上的表现可能不佳。如果效果不佳,那么您可以使用 SVG 背景来实现此目的,否则,您可能不得不退回到使用传统的预渲染背景图像。
关于google-chrome - CSS 多背景工作不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15886689/