Juddling Juddling - 8 months ago 55
CSS Question

Multiple background images positioning

I've got three background images, all of width 643px. I want them to be set out like so:

  • top image (12px height) no-repeat

  • middle image repeat-y

  • bottom image (12px height) no repeat

I can't seen to do it without getting them to overlap (which is a problem because the images are partially transparent), is something like this possible?

background-image: url(top.png),

background-repeat: no-repeat,

background-position: left 0 top -12px,
left 0 bottom -12px,
left 0 top 0;

Answer Source

Your problem is that the repeat-y is going to fill the whole height, no matter where you position it initially. Thus, it overlaps your top and bottom.

One solution is to push the repeating background into a pseudo element positioned off of the container by the 12px at the top and bottom. The result can be seen here (the opacity in the demo is just to show that there is no overlap going on). Without opacity, see here. The relevant code (tested in CSS3 browsers: IE9, FF, Chrome):


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;

If you needed or wanted IE8 support (which does not support multiple backgrounds), then you could put the top background in the main div, and put the bottom background in by using the div:after pseudo element positioned to the bottom of the container.