Anchoring CSS Repeating Background Image

2019-05-15 07:37发布

问题:

I have a webpage with a header banner in the following configuration:

<---Repeating Image Left--><---Banner Image---><---Repeating Image Right--->

The page is designed with fixed width content, but the banner spans the entire width of the browser window (thus the reason for including repeating images on the left and right).

The two repeating images are different and they are also not standard background images which can be positioned where-ever. Instead, the left image needs to be anchored/stuck to the left-hand side of the banner image and then repeat itself leftwards, from that point, as the browser window is expanded. Likewise, the right image needs to be anchored/stuck to the right-hand side of the banner image and repeat itself rightwards from that point.

Using the pure background-image: property with the repeat-x set does not work, as the image will be repeated/tiled from the left-hand side of the browser window, rather than from the left/right hand side of the banner image outwards in the desired direction.

Any help to achieve the desired effect would be appreciated.

回答1:

You can do this with a single styled element, yes:

#banner {
  height: 50px;
  width: 50%; margin: 0; padding-right: 50%;
  background-image:url('banner.png'), url('left-bg.png'), url('right-bg.png');
  background-clip: padding-box, content-box, content-box;  
  -webkit-background-clip: padding-box, content-box, padding-box; 
  background-origin: padding-box, content-box, padding-box;
  background-position: center, right, center;
  background-repeat: no-repeat, repeat-x, repeat-x;
}

The element has three backgrounds. The trick is in getting different ones to appear on the left and right, which I've done by adding 50% padding on the left. The left hand side is "padding box" and the right is "content box".

You might want to make the first background an <img> so you can give it a title tag -- if you do then it'll appear only in the right-hand 50% of the window so you'll have to left align it and use position:relative; left:-250px to get it back into the middle.

Lastly, the background images are locked to the middle of the window, not the edge of the banner, but you can fix that by changing the images themselves.



回答2:

Can you provide a URL to check the site? It sounds like you'll need to experiment with the css property:

background-position {x, y}


回答3:

banner
{
background-image:url('image.gif');
background-repeat:repeat-x;
vertical-align: middle;
text-align: center; /*optional*/
}

i don't know if this works, but it's worth a try.