多个背景图像定位

Jud*_*ing 36 css background background-image css3 background-position

我有三张背景图片,全宽643px.我希望他们像这样出发:

  • 顶部图像(12px高度)不重复

  • 中间图像重复-y

  • 底部图像(12px高度)没有重复

如果不让它们重叠(这是一个问题,因为图像是部分透明的),我似乎无法做到这一点,这样的事情可能吗?

background-image:    url(top.png),
                     url(bottom.png),
                     url(middle.png);

background-repeat:   no-repeat,
                     no-repeat,
                     repeat-y;

background-position: left 0 top -12px,
                     left 0 bottom -12px,
                     left 0 top 0;
Run Code Online (Sandbox Code Playgroud)

Sco*_*ttS 50

你的问题是repeat-y无论你最初在哪里定位它都会填满整个高度.因此,它与您的顶部和底部重叠.

一种解决方案是将重复背景推入位于容器12px顶部和底部之外的伪元件中.结果可以在这里看到(演示中的不透明度只是为了表明没有重叠).没有不透明度,请看这里.相关代码(在CSS3浏览器中测试:IE9,FF,Chrome):

CSS

div {
    position: relative;
    z-index: 2;
    background: url(top.png) top left no-repeat, 
                url(bottom.png) bottom left no-repeat;
}

div:before {
    content: '';
    position: absolute;
    z-index: -1; /* push it to the background */
    top: 12px; /* position it off the top background */
    right: 0;
    bottom: 12px; /* position it off the bottom background */
    left: 0;
    background: url(middle.png) top left repeat-y;
}
Run Code Online (Sandbox Code Playgroud)

如果您需要或想要IE8支持(不支持多个背景),那么您可以将顶部背景放在主div中,并使用div:after位于容器底部的伪元素放置底部背景.


kiz*_*izu 6

如果您可以向块添加填充/边框等于您想要定位的背景而不重叠其他块,您可以使用background-clip&background-origin来定位填充/边框上方的顶部和底部背景,以及内容/填充上的重复背景+内容.

这是一个例子:http://dabblet.com/gist/2668803

对于您的代码,您可能需要添加以下内容:

padding: 12px 0;
background-clip: padding-box, padding-box, content-box;
background-origin: padding-box, padding-box, content-box;
Run Code Online (Sandbox Code Playgroud)

要么

border: solid transparent;
border-width: 12px 0;
background-clip: border-box, border-box, padding-box;
background-origin: border-box, border-box, padding-box;
Run Code Online (Sandbox Code Playgroud)

你会得到你需要的东西.如果你不能得到填充/边框,像ScottS提到的伪元素将完美地工作.