what's the correct shorthand syntax when using

2019-07-15 02:42发布

I need to attach multiple backgrounds to an element via CSS and I can't use :before/:after.

I'm wondering what the correct syntax to use multiple CSS background image is.

There is a bunch of suggested ways I found, like here or here, but I can get neither of these:

background: url(…) 0 0 repeat, url(…) 5px 5px no-repeat #FFF;
background: url(…) 600px 10px no-repeat, url(…) 10px 10px no-repeat;

to work.

This is what I currently have:

background-image: rgba(0, 0, 0, 0.4) url("img/icons-18-white.png") no-repeat 0% 50%,linear-gradient( #9ad945, #7eb238 );

which is ignored. Only when I supply the pure url, it works:

background-image: url("img/icons-18-white.png") , linear-gradient( #9ad945, #7eb238 );

Question:
I'm specifically looking for a way to set background-size/position/repeat per image, so if someone could point me to the correct syntax, would be really nice!

EDIT: Adding scroll and replacing background-image with background

background: rgba(0, 0, 0, 0.4) url("http://code.jquery.com/mobile/1.3.0/images/icons-18-white.png") no-repeat scroll 0% 50%, linear-gradient( #9ad945, #7eb238 );

does not work.

1条回答
时光不老,我们不散
2楼-- · 2019-07-15 03:24

There are two main issues with what you have that prevent it from working:

  • The shorthand property is background, not background-image.

  • The background color, which in your case is rgba(0, 0, 0, 0.4), must be specified last.

If the shorthand syntax ends up too confusing, you can always set the individual properties separately, passing them the same number of comma-separated values corresponding to the number of background layers (CSS gradients are considered to be images). However if you set background-color you may only specify it once.

Remember that when specifying multiple backgrounds, the order in which they are drawn is first to last, top to bottom. This is why the color is expected to come last in a shorthand declaration. This section of the spec describes it, while this section contains the full syntax:

Value: [ <bg-layer> , ]* <final-bg-layer>

Where

<bg-layer> = <bg-image> || <position> [ / <bg-size> ]? || <repeat-style> || <attachment> || <box>{1,2} 

<final-bg-layer> = <bg-image> || <position> [ / <bg-size> ]? || <repeat-style> || <attachment> || <box>{1,2} || <'background-color'>

Details about layering in individual properties can be found in their respective sections.

If you're trying to superimpose the background graphic over an rgba() color, you may not be able to add a gradient beneath that layer without applying the gradient to a :before box instead. Alternatively, if you mix the 40% black color into the gradient stops themselves, you can remove the rgba() color altogether leaving just the graphic and the gradient.

查看更多
登录 后发表回答