Tuesday, August 9, 2011

Layering Multiple Background Colors/Images

While goofing around with inline CSS I accidentally stumbled across a way to use multiple background colors and/or images. For this post I'm using only colors to keep the sample code short and easily read. I see no reason why you couldn't break this out of inline CSS by assigning each div a different class or id. This is not done with a table or multiple tables, it's purely CSS.

<div style="width:98%;height:450px;position:relative;border:3px ridge black;margin:auto;">
<div style="height:90%;width:90%;background-color:green;position:relative;margin:auto;top:5%;border:2px solid black;">
<div style="height:80%;width:80%;background-color:blue;position:relative;;margin:auto;top:10%;border:1px dashed black;">
<div style="height:70%;width:70%;background-color:red;position:relative;margin:auto;top:15%;border:1px dotted black;">
</div></div></div></div>

The code above produces this:

4 comments:

  1. Very interesting, Jeff, thank you.... you think that with this way we can use also background images ?

    Gabriela

    ReplyDelete
    Replies
    1. Yes, Gabriela. I think that you can. The concept is exactly the same so I see no reason why it wouldn't work.

      You can actually use multiple background images already, just by adding different background declarations to your CSS. For example:
      #exampleA {
      background: url(small-image1.png) left top no-repeat, url(small-image2.png) right bottom no-repeat, url(main_background.jpg) left top;
      }

      You just separate each background declaration with a comma. Each successive image appears beneath the one preceding it in the code. In the example above, main-background.jpg would appear as the main background, small-image2.png would appear on top of the main background at bottom right and small-image1.png would appear on top of the main background at top left. You just stack as many as you want to and position accordingly.

      Of course, the IE will be the problem there, only IE9 and above will comprehend what you've done and render it properly.

      Delete
    2. however using the method in my original post should work in any browser. It's just a bit more confusing and time consuming.

      Delete
    3. Thank you for the explanation, Jeff, it is super :)

      Delete

});