Monday, February 4, 2013

How to Use CSS3 Multiple Backgrounds

How to Use CSS3 Multiple Backgrounds:
Adding background image with CSS is nothing new, this feature has been there since its inception. But we were limited to only add one image in one declaration block. Now, CSS3 is raising the stakes by proiding you the option of adding multiple backgrounds.

How to use it?

In the old days, when we need to add more than one background image, we most likely will interrupt the HTML structure as well as add more classes to achieve the desired result through CSS, something like this.
.overcast1 {
 background-image: url("images/overcast.png");
 background-position: 150px 25px;
}
.rainbow {
 background-image: url("images/rainbow.png");
 background-position: 200px 10px;
}
.overcast2 {
 background-image: url("images/overcast.png");
 background-position: 250px 25px;
}
.sunny {
 background-image: url("images/sunny.png");
 background-position: 100px 10px; 
}
The code above is clearly superfluous. In CSS3, this code can be concatenated in single background-image property, as follows;
.weather {
  width: 500px;
  height: 280px;
  margin: 50px auto;
  background-image: url("images/overcast.png"),
     url("images/rainbow.png"), 
     url("images/overcast.png"), 
     url("images/sunny.png");
  background-position: 150px 25px, 
     200px 10px, 
     250px 25px, 
     100px 10px;
  background-repeat: no-repeat;
}
In this code, we have added the same four images with different positions in accordance, producing this stunning results.

Adding Animation Effect

Furthermore, we can make the result even more stunning by adding CSS3 Animations. To make the coding simpler, we are going to use only the standard syntax from W3C, but remember that the browsers – IE9, Firefox, Opera, Chrome, and Safari – still need their respective prefixes for this to work.
Recommended Reading: Creating Advanced “Marquee” With CSS3 Animation
@keyframes weather { 
  0% {
    background-position: 120px 25px, 200px 10px, 280px 25px, 80px 10px;
  }
  100% {
    background-position: 150px 25px, 200px 10px, 250px 25px, 100px 10px;
  }
}
Once we have specified the @keyframes, then we only need to add the animation with the keyframe name to the intended selector, in this case .weather;
.weather {
  animation: weather 5s;
}
That’s it, we can now see the animation effect in action from the links below as well as download the source for further examination.s

Browser Supports

According to CanIUse.com, CSS3 Multiple Backgrounds is already supported in the following browsers; IE9+, Firefox 3.6+. No luck with Internet Explorer 8. But if you can assure yourself that you can leave IE8 behind, you can use CSS3 Multiple Backgrounds right now.

Further References

No comments:

Post a Comment