I am trying to use the technique described as technique #2 at the following URL: http://css-tricks.com/perfect-full-page-background-image/
to set a web page background image that shrinks in size when the window is resized.
My HTML is as following
<div class="bg">
<img src="images/bg.jpg" alt="">
</div>
And my style definition is as following.
.bg {
z-index: -1;
position: fixed;
top: -50%;
left: -50%;
width: 200%;
height: 200%;
}
.bg img {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
min-width: 50%;
min-height: 50%;
}
This works perfectly when the image is smaller than the screen and it needs to be sized up. But in case of shrinking a big image, it doesn't work and I just get a huge image centred on my screen.
I need my image to be able to shrink, cover the entire background, preserve aspect ration. I cannot use body bg or whatsoever because I need to be able to change the image in a slideshow.
EDIT:
I HAVE to have the HTML structure as <div><img/></div>
EDIT 2: The reason I cannot change the structure (or at least that's what I think) is that I am using script at: http://malsup.github.com/jquery.cycle.all.js to cycle several images, and that script doesn't allow me to change anything of the way the HTML is structured. If anyone knows how to use it with background images or suggest a totally different script that would be much appreciated.
If you have to use <img>
tags to produce the image, simply delete the height
declaration from your CSS; the image should maintain aspect ratio and resize appropriately if you just have width
specified. (Alternatively you could specify height
and delete width
as well, but specifying width
is the industry norm.
For a CSS background method, try this, instead:
.bg {
background-image: url('images/bg.jpg');
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center center;
background-clip: border-box;
background-origin: padding-box;
-moz-background-size: cover;
background-size: cover;
}
It requires CSS3, but will work in somewhat-old browsers (-moz-background-size
is for FF3.6; FF4+ uses the default background-size
). This method uses the CSS background-image
property which is preferred to your method.
The reason for this is that the background image is not part of the meaningful content of your site page, but rather part of the styling (it's a background image, so it belongs in the background). Therefore, it should be handled using Cascading Style Sheets.