8

Today I learned CSS3 supports multiple backgrounds, which is awesome. What I'd really like is the ability to combine multiple backgrounds on the fly, EG:

.Watermarked{
  background: url('text/logo.png') bottom right no-repeat;
}

HTML:

<div class="Watermarked" 
     style="background:url('photos/very_pretty_sunset.jpg') 0 0 no-repeat;">
...

Somehow produces the computed style:

 background: url('text/logo.png') bottom right no-repeat,
             url('photos/very_pretty_sunset.jpg') 0 0 no-repeat;    

Of course I can hard code the extra background style or add it using jquery. I am seeking that sweet, pure, CSS-only solution.

Answered

Accepted thirtydot for the pure CSS answer- "You can't".

It's worth highlighting that if you're working with SASS (Rails 3.1, etc), the hard-coded styles are more palatable through variable use:

$watermarkImage: url('text/logo.png') left top no-repeat;
...
#very_pretty_sunset{
  background: $watermarkImage, url('photos/very_pretty_sunset.png') right bottom no-repeat;
}
Community
  • 1
  • 1
RSG
  • 7,013
  • 6
  • 36
  • 51

3 Answers3

5

Pseudo selectors :before or :after can be used to add a new background layer

/* This is your element that needs an additional background */
.myElement {
  position: relative;
  z-index: 1;
}
/* This is your background layer */
.myElement:before {
  position: absolute;
  z-index: -1;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: /* Define your bg */;
}
Semra
  • 2,787
  • 28
  • 26
5

You can't do that with CSS.

Whichever background is declared with higher specificity will completely override the other one.

thirtydot
  • 224,678
  • 48
  • 389
  • 349
2

PREREQUISITE

  1. width of the div = width of the img - border-image img width
  2. height of the div = height of the img - border-image img height
  3. border-image img height = border-bottom-width
  4. border-image img width = border-right-width
  5. your border image must be transparent (obvious)

CSS

.Watermarked {
    -moz-border-image: url('text/logo.png') 0 100% 100% 0;
    -webkit-border-image: url('text/logo.png') 0 100% 100% 0;
    -o-border-image: url('text/logo.png') 0 100% 100% 0;
    border-image: url('text/logo.png') 0 100% 100% 0;
}



box-sizing alternative

PREREQUISITE

  1. border-bottom-width = logo.png height
  2. border-right-width = logo.png width
  3. your border image must be transparent (optional)

CSS

.Watermarked {
    -moz-border-image: url('text/logo.png') 0 100% 100% 0;
    -webkit-border-image: url('text/logo.png') 0 100% 100% 0;
    -o-border-image: url('text/logo.png') 0 100% 100% 0;
    border-image: url('text/logo.png') 0 100% 100% 0;
   -moz-box-sizing:    border-box;
   -webkit-box-sizing: border-box;
    box-sizing:        border-box;
}
Knu
  • 14,806
  • 5
  • 56
  • 89