Monday, 7 March 2011

CSS: Backgrounds with CSS3

One of the most searched effects for web sites today is the background image covering all the visible area. I've already explained a method to achieve that in the past (Making background image fit any screen resolution). With CSS3 there are a set of new property that can handle it quite easily. Let's see them.

The background-size property
The background-size property defines the size of a background image (ah!). You can set the image size in pixels or percentages. With percentage, the size will be relative to the container.
div
{
background:url(example.gif);
-moz-background-size:100% 100%; /* Firefox */
background-size:100% 100%;
background-repeat:no-repeat;
}

In the above example, our gif will fill completely the container (any div in the page); the image will be stretched and eventually distorted.

Compatibility
The background-size property is completely compatible with Chrome, Opera and Safari. Firefox uses the -moz-background-size property, while Internet Explorer (as usual) is not recognizing the property.

The background-origin property
This is interesting! The background-origin property defines the positioning area of the image. It has three possible parameters: content-box, padding-box, or border-box.

Compatibility
The background-origin property works only in Opera, Chrome and Safari.

Multiple images
CSS3 allows the use of multiple images:
body
{
background-image:url(example1.gif),url(example2.gif);
}
The two images (example1.gif and example2.gif) will be put one on top of the other.

Compatibility
Multiple images work with Firefox, Opera, Chrome and Safari. Again... no Internet Explorer.

No comments:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.