dimanche 27 mai 2012

CSS: Making background image fit any screen resolution (revised)

After the great success of my previous post "CSS: Making background image fit any screen resolution" I would like to share a new version of the same.
The following is just a revised post, so basically it contains the same code, but with a twist.
The point is that many readers have asked me how they could have a scrolling page while the image stays stretched and fixed.
Well... I suppose you could get there and find how to do it by yourself, but I thought I could share it anyway, maybe for those of you that are not really experienced enough already (time to grow ladies and gentlemen - I'm joking... obviously...). We are going to use a few CSS lines and two HTML tags.

Ok, let's get into it!

The image
As I explained already in my previous post, just place your image just before the </body> tag:

<div align="center" ><img src="images/BG.jpg" border="0" class="bg" ></div>
The image has a class="bg". That's where most of the magic is.
Now, just before the above snippet, place a div: that will be our main container. Just to be clear, we are going to put all the rest of the page (articles, images and so on) inside that div. We are going to style it as well, afterwards.
<div class="maincontainer">Place your content here!</div>
Let's see how to style those two elements.

The CSS
What we basically need is:
1) place the image in the background;
2) place the main container on top.
Simple as that. There's a difference from the my previous post: the image is not absolutely positioned.
Let's see the code:
<style type="text/css">
.bg {
    width: 100%;
    position: fixed;
    top: 0;
    left: 0;
    z-index: -5000;
    height: 100%;
}
.maincontainer {
    height: 1000px;
    z-index: 5000;
}
</style>
First of all, the main container has an height of 1000px. That is only for the example: you do not need it because the div will stretch according to its content.
The image (.bg class) has a fixed position and a -5000 z-index, while the main container has 5000 value for z-index. That is because we need the image to stay in the background.

That's all folks! Try the example with your testing server and see how it works... after that let me know what you think...

0 Responses to “CSS: Making background image fit any screen resolution (revised)”

Enregistrer un commentaire

All Rights Reserved Blogging Tips | Blogger Template by Bloggermint