Friday 20 April 2012

CSS: backgrounds with CSS3

   


As I can see from the web thought statistics, there's a increasing interest in how to manage backgrounds with CSS and specifically with CSS3. So I decided to write down the following short tutorial. We are going to explore three interesting CSS properties: background-clip, background-origin and background-size.
I know, I've partially covered the subject in another post, however here we are going to see it more in depth.

Are you ready? Ok then, follow me...

Background-clip
The background-clip property is used to determine the background area. It accepts three possible values:
1) padding-box;
2) content-box;
3) border-box.
The three values will have different effects.
With padding-box the background colour will cover the padding area excluding the borders:

Padding-box

With content-box the background colour will cover the content area:

Content-box

With border-box the background colour will cover the area to the borders:

Border-box

The CSS used in the examples:
.yourClass
{
width:50%;
padding:15px;
background-color:red;
background-clip:padding-box;
-webkit-background-clip:content-box; /* Safari */
border: 1px solid;
}
Just change the background-clip value. In the last example the border is set to 5px dotted.

Background-origin
The background-origin property is used to determine the position of a background image:
.yourClass
{
background-image:url('test.jpg');
background-repeat:no-repeat;
background-position:left;
background-origin:content-box;
}
It can have the same three values as background-clip: 
1) padding-box;
2) content-box;
3) border-box.
According to the chosen value, the background image will stay relatively to the padding, the content or the border, following the same behaviour as seen above for the background-clip.

Background-size
The background-size specifies the size of the background image:
.yourClass
{
background:url('test.jpg');
background-size:100px 50px;
background-repeat:no-repeat;
It accepts three values:
1) length (we can specify the length and width of the image like in the above example; the size can be in pixels or percentages);
2) cover (the image will fit into the content area with its smallest size);
3) contain (the image will fit into the content area with its largest size).

Now you can use the above properties to manage your background images or colour fills. It is to be noted that the three properties are fully working in IE9+, FF4+, Opera, Chrome and Safari 5+ apart from the background-clip property which need the -webkit prefix for Safari (as seen in the first examples).

I hope you enjoyed the post, and please do share your thoughts as usual.

0 thoughts:

Post a Comment

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

However, I do answer to all the comments.