This post was originally published on August 21, 2009 and is now updated as it has been entirely revised. Both original methods are removed and now replaced by four new methods.
The goal here is a background image on a website that covers the entire browser window at all times. Let’s put some specifics on it:
- Fills entire page with image, no white space
- Scales image as needed
- Retains image proportions (aspect ratio)
- Image is centered on page
- Does not cause scrollbars
- As cross-browser compatible as possible
- Isn’t some fancy shenanigans like Flash
Awesome, easy, progressive CSS way
We can do this purely through CSS thanks to the background-size
property now in CSS. We’ll use the html
element (better than body
as it’s always at least the height of the browser window). We set a fixed and centered background on it, then adjust it’s size using background-size
set to the cover keyword.
html {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Works in:
- Safari 3+
- Chrome Whatever+
- IE 9+
- Opera 10+ (Opera 9.5 supported background-size but not the keywords)
- Firefox 3.6+ (Firefox 4 supports non-vendor prefixed version)
Update: Thanks to Goltzman in the comments for pointing out an Adobe Developer Connection article which features some code to make IE do cover backgrounds as well:
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";
But careful, reader Pierre Orsander said they tried this and had some problems with links on the page going dead.
Update: Matt Litherland writes in to say that anyone trying to use the above IE filters and having problems with scrollbars or dead links or whatever else (like Pierre above) should try not using them on the html
or body
element. But instead a fixed position div with 100% width and height.
CSS-only technique #1
Big thanks, as usual, to Doug Neiner for this alternate version. Here, we use an inline element, which will be able to resize in any browser. We set a min-height
which keeps it filling the browser window vertically, and set a 100% width
which keeps it filling horizontally. We also set a min-width
of the width of the image so that the image never gets smaller than it actually is.
The especially clever bit is using a media query to check if the browser window is smaller than the image, and using a combo percentage-left and negative left margin
to keep it centered regardless.
Here is the CSS:
img.bg {
/* Set rules to fill background */
min-height: 100%;
min-width: 1024px;
/* Set up proportionate scaling */
width: 100%;
height: auto;
/* Set up positioning */
position: fixed;
top: 0;
left: 0;
}
@media screen and (max-width: 1024px) { /* Specific to this particular image */
img.bg {
left: 50%;
margin-left: -512px; /* 50% */
}
}
Works in:
- Any version of good browsers: Safari / Chrome / Opera / Firefox
- IE 6: Borked – but probably fixable if you use some kind of fixed positioning shim
- IE 7/8: Mostly works, doesn’t center at small sizes but fills screen fine
- IE 9: Works
CSS-only technique #2
One rather simple way to handle this is to put an inline image on the page, fixed position it to the upper-left, and give it a min-width
and min-height
of 100%, preserving it’s aspect ratio.
<img class="bg" src="images/bg.jpg" alt="">
.bg {
position: fixed;
top: 0;
left: 0;
/* Preserve aspet ratio */
min-width: 100%;
min-height: 100%;
}
However, this doesn’t center the image and that’s a pretty common desire here… So, we can fix that by wrapping the image in a div. That div we’ll make twice as big as the browser window. Then the image will be placed, still preserving it’s aspect ratio and covering the visible browser window, and the dead center of that.
<div class="bg">
<img src="images/bg.jpg" alt="">
</div>
.bg {
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%;
}
Credit to Corey Worrell for the concept on this one.
Works in:
- Safari / Chrome / Firefox (didn’t test very far back, but recent versions are fine)
- IE 8+
- Opera (any version) and IE both fail in the same way (wrongly positioned, not sure why)
- Peter VanWylen wrote in to say that if you add the image via JavaScript, the img needs to have width: auto; and height: auto; to work in IE 8, 9, or 10.
Update January 2018: Trying to get this to work on Android? JL García wrote to me saying he needed to add height: 100%; and overflow: hidden; to the html element to get it to work. The full snippet being:
html {
background: url(images/bg.jpg) no-repeat center center fixed;
background-size: cover;
height: 100%;
overflow: hidden;
}
I tested it, and it seemed totally correct. Without it / With it.
jQuery method
This whole idea becomes a lot easier (from a CSS perspective) if we know if the aspect ratio of the image (inline we intend to use as a background) is larger or smaller than the current aspect ratio of the browser window. If it is lower, than we can set only the
width
to 100% on the image and know it will fill both height and width. If it is higher, we can set only the height
to 100% and know that it will fill both the height and width.
We have access to this information through JavaScript. As usual around here, I like to lean on jQuery.
<img id="bg" src="images/bg.jpg" alt="">
#bg { position: fixed; top: 0; left: 0; }
.bgwidth { width: 100%; }
.bgheight { height: 100%; }
$(window).load(function() {
var theWindow = $(window),
$bg = $("#bg"),
aspectRatio = $bg.width() / $bg.height();
function resizeBg() {
if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
$bg
.removeClass()
.addClass('bgheight');
} else {
$bg
.removeClass()
.addClass('bgwidth');
}
}
theWindow.resize(resizeBg).trigger("resize");
});
This doesn’t account for centering, but you could definitely alter this to do that. Credits to Koen Haarbosch for the concept behind this idea.
Works in:
- IE7+ (could probably get in IE6 with a fixed position shim)
- Most any other desktop browser
Update (June 2012): Reader Craig Manley writes in with a technique to load an appropriately sized background image according to screen. As in, don’t load some huge 1900px wide background image for an iPhone.
First, you’d make images like 1024.jpg
, 1280.jpg
, 1366.jpg
, etc. Then, instead of loading an image, you’d load a shim.
<img id="bg" style="position: fixed; left: 0; top: 0;" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" alt="">
If you don’t like the gif shim (personally I think it’s OK because it’s not “content” it’s a background) you could load up one of the real images instead. This code will account for that.
Then you test the screen width and set the src
of the image based on it. The code below does it on resize, which you may or may not want. You could just run the code once if you wanted.
(function() {
var win = $(window);
win.resize(function() {
var win_w = win.width(),
win_h = win.height(),
$bg = $("#bg");
// Load narrowest background image based on
// viewport width, but never load anything narrower
// that what's already loaded if anything.
var available = [
1024, 1280, 1366,
1400, 1680, 1920,
2560, 3840, 4860
];
var current = $bg.attr('src').match(/([0-9]+)/) ? RegExp.$1 : null;
if (!current || ((current < win_w) && (current < available[available.length - 1]))) {
var chosen = available[available.length - 1];
for (var i=0; i<available.length; i++)="" {="" if="" (available[i]="">= win_w) {
chosen = available[i];
break;
}
}
// Set the new image
$bg.attr('src', '/img/bg/' + chosen + '.jpg');
// for testing...
// console.log('Chosen background: ' + chosen);
}
// Determine whether width or height should be 100%
if ((win_w / win_h) < ($bg.width() / $bg.height())) {
$bg.css({height: '100%', width: 'auto'});
} else {
$bg.css({width: '100%', height: 'auto'});
}
}).resize();
})(jQuery)</available.length;>
Note that screen width isn’t the only possible good information to have when choosing an image size. See this article.
Enjoy
If you use this, please feel free to leave what technique you used and if you altered it in any way in the comments below. Always cool to see techniques “in the wild.”
Just for posterity sake, there is another example in here called table.php
which uses an old technique that used to be a part of this article. It had some cleverness, but wasn’t quite as good as either CSS technique now presented above.
Other resources
- Vegas jQuery plugin (Jay Salvat)
- How to Change a Background Image’s Opacity (DigitalOcean)
When the background-image gets upscaled it seems like it’s pretty heavy for Firefox (maybe other browsers too) and if you scroll through the site there is an obvious delay there.
Nice effect though, thanks!
Yep. In Chome there is a delay.
Nice follow up to the previous article. I personally wouldn’t have thought of using a table – the bogeyman of web design!
Works nicely though.
This is awesome! very clear in w200% and h200% then -50% positioning!
Table is perfect fine because its only holding a image. The content you concern about with accessibility is on the DIV.
Fine!? A table is fine if you like to poop all over semantics and proper use of HTML elements.
This solution is ugly as sin, a javascript workaround would be far more elegant (if done properly).
did he say “poop”? :D must have kids. haha
It never ceases to amaze me how much hate tables have generated within the design community :)
@ Josh #2
Blatant incorrect use of tables have generated a lot of hate and rightly so.
Oh, I think that’s almost the definition of hate, isn’t it? It makes you sort of irrational.
The problem with tables was lots and lots of them everywhere, for no reason.
This, OTOH, is a beautiful solution with a tiny little table. Oh, who cares?! :-)
I agree that it’s fine – it’s not as though in a real world situation you would be entering the site for awards.
Sure, divs are purposely designed for layout. But in a business sense (which is how we all put food on the table), sometimes the quicker way is using a table here and there.
Unless otherwise specified, I sincerely doubt that a client or employer would care – I haven’t come across one.
This is a fantastic solution + especially that it is cross browser compatible which is far more important.
tables … geeze …. those who moan about how bad it is generally have less than perfect websites themselves … lol …. nothing at all wrong with tables if used correctly and this is a prime example of very good use.
WELL DONE and thanks
thought about how to do this yesterday, and then you post this today. This is really great!
Thanks
nice tips. btw, how trick if the image in code css?
Just a little nitpick,
Fills entire page with image, no white space
On the Demo, when the window is less then 1125px wide there IS white space on top and bottom.
I think this space is more likely to appear on a user’s screen then when there is white when the window is bigger then 2560px (with a big image and overflow:hidden) – the latter is not the case in this demo, but is here
In Chrome 2.0.172.39 i see background at top and bottom of page (on Your example and on http://ringvemedia.com/), and in Opera 9.64 i see scrollbars on Your example. On http://ringvemedia.com/ scrollbard doesn’t show.
The latest Opera looks fine to me, but indeed there is a bug in Chrome (mac). I’m gonna hold off on sweating that until there is a final mac version I can test on.
http://img29.imageshack.us/gal.php?g=chromeq.jpg these are screenshots taken from my home desktop, but problems are the same @ work, there i’m on XP, here on Win 7.
Opera screenshot is from 10beta, but i’ve got the same problem on 9.64.
That was taken in the few minutes while I was working on a new idea to fix the focus/scrolling problem…
But Opera is still kinda borked.
Man, the Opera users really come out of the woodwork when you post a technique like this.
Thanks for taking a look and breaking this down. I found an earlier method listed on this site, too, https://css-tricks.com/how-to-resizeable-background-image/ but I ended up using the method Anders uses on http://www.cssplay.co.uk/layouts/background.html.
Seems there are always several ways to accomplish the same thing….still not sure how tables works in this case but fun to take a look nonetheless.
Thanks!
Doug
The CSSPlay method looks to resize the image though, which can be undesirable.
Anders method doesn’t preserve the aspect ratio does it?
I agree with Chris that the distorted aspect ratio is quite undesirable.
It’d be great if we could do this without the use of a “layout-table”, BUT this is a fantastic effect and perfect for photo blogs, portfolios, etc.
Thanks for sharing!
Nice effect Chris, I’ll definately get some use out of this one. Good job.
This technique (at least the demo and the ringvemedia site) don’t work very well in Safari 4.0.2
The horizontal scaling sort of works but the vertical stuff doesn’t.
Screenshot
It seems to be the min-height attribute on the image that isn’t taking in Safari 4. Not sure what the solution is going to be there. JavaScript might need to get involved, unfortunately.
Nice proof of concept, I like these types of posts. Thanks.
Another way to do this trick that i use, is to use jquery tlike this
to explain this, with jquery i’m getting the height and width of the window then using php gd i’m resizing my background to the good size
What kind of success have you had doing it with jquery and php? Does it work in all browsers ?
This is a really bad way to handle full screen backgrounds, geekbay. I take it you’d run this on $(window).resize(), not $(document).ready()? This means you’ll call a PHP script and have GD resize the image every single time the window is resized! Do you know how much memory that will use?!
just a little glitch it’s:
$(body).style(‘background’,’url(phpthumb.php?src=bg.jpg&w=’+w+’&h=’+h+’)’);
Pretty clever =)
Would you mind explaining this a little more? Is this function inside the document ready function? A little more insight in terms of implementation would help me understand.
Thanks
From what I can see, this either:
a) doesn’t resize with the window
or b) re-requests the image whenever you change the window size.
More importantly, this technique prevents the browser caching the background image – which, for big images like these – is critical.
Very cool trick. Can’t CSS3 implement this also? I know it’s not friendly w/ IE yet. Just curious.
I have seen this before too. Was inspired by it originally..
Hmmm, on FF3.5, if I press “space” the whole page scrolls…
I fixed the space bar issue by appending a hidden input with javascript and setting the focus to that. Kinda hacky but fixes the bug for now.
Alright I documented the current known bugs at the bottom of the article. If you find fixes or more bugs, let me know.
The page scroll can actually be done with the space bar, but also with the arrow keys, for horizontal and vertical scrolling.
I suppose it’s a focus problem; anyway for accessibility it would be better to have the focus on the center element.
So it means… javascript.
The only problem I see is the image definition. If you load a huge image into a small window, rescaling may make it look funny, or a image let’s say 1280px large will show big pixels on a huge screen. I generally load a standard image of 1280px as background and overload a bigger one in Ajax if the screen is wider. There is no rescaling in that case but at least there is an absolute control over the background image quality.
This seemed to work fine for me: Supersized
This reminds me of the new WPC2 system I just recently created.
I can’t say too much, but this does make me want to recreate your example with my technique used for resizing the WPC page to see if most of your bugs disappear. If I have any success I’ll reply to this comment and let you know
This is awesome! I thought this was only possible using flash. Thx for the post. Will definitely be using this for a photo gallery page.
The Image bar comes up on IE 6 if you hover over the image
i.e. the Save print etc. buttons that IE overlays.
You might want to kill that, it ruins the effect, Im sure there is some way to do that
Very nice, will give it a try. Thanks!
Was looking at this site’s solution for background images too
http://www.type3digital.com/
Bump – how did they do this?
Yup that question stayed in my head too…:D
I will be using this with one of my clients. Really beats the Javascript I was using. Thanks!
In the demo, in IE8 at least, the mousewheel only scrolls the content when the cursor is inside the white text container, and it’s somewhat sluggish at large resolutions.
Great that it works with CSS, but too many bugs to be used effectively.
I use supersize 2.0 for the same effect (also has transition). I used it here.
Agreed. Supersize 2.0 looks great. Does IT have any bugs or inconsistencies? What if a user doesn’t enable JavaScript?
There is a scroll bar in Opera 9.6, and it scrolls down to white space
Thanks for this – spookily just when I needed it!
There is also a vertical scrollbar in Opera 10b3, but it’s for the text – however, if I scroll down (without clicking the text first) it will scroll the image instead of the text.
In fact, if I middle click on the page, I can scroll to reveal white space both on the y- and x-axis in Opera, Firefox 3.5, Chrome, Safari4 and IE8. This is also the case for whatstheweather, but then only in the right-hand side.
~ Nix
the scrollbar ‘bug’ in FF3.5 isn’t a bug. that’s a keyboard shortcut to scroll down on any page. try it on this page, or google news, or where ever. the shortcut works in Chrome and IE8, too.
The “bug” refers to this technique, not Firefox itself.
I do get whitespace on the top and bottom if the browser is taller than wider of the image proportions. This needs to zoom-center.
can someone explain to me why exactly it is necessary to use a table for this effect? I am assuming that there is some innate abilities a table has that make this possible, but I am not sure what. Learning xhtml from the start I am not very table savvy ;)
Hmm, it’s nice in theory, but current browsers seem to be rather laggy on resize and scroll – And unless you use a high resolution image, chances are you’re going to see very unprofessional artifacts. Good to know for the future though =)
Hi Chris. Thanks for posting this. The NorthFace site has similar functionality but it looks like they use a flash solution.
I love this! This is one of those CSS Tricks I love to see appear rss feed! Alot of people don’t seem to like this, because of little bugs and the evil devil child of the internet design tables. My personal view on this is I hate tables but if it achieves the job without the use of flash or javascript then a table is okay. Semantics is only good and a guide to follow if you can afford it. Lets all remember that the objective is to design nice looking working sites. And these are some damn nice css tricks!
Thanx for thip great tip! I think, i will be use this trick on many sites;) This trick work on ie 5.5. Good Job!
I do something like this:
http://dump.myxcp.net/de…..ound.html
Lacks being centered vertically but works well regardless. Or you can make it 100% height and 100% min-width (then it can be centered horizontally easily).
@monkey56657 I did notice on your example that if your browser is not resized in proportion to the image, it does not cover the entire background vertically.
There’s some funkyness when the browser gets really short in technique 1.
but Technique 2 works great :) Thanks.
In technique 2: If you set the img.bg bottom: 0 instead of top: 0, you can anchor the image to the bottom of the browser window instead of having it anchored to the top. If you had a city-scape or other bottom-designed image, this would become very important.
Technique 2 is very good addition to the article.
@Chris: Could you somehow indicate that this article has been updated ?
Thanks for posting this. One question, why use a table? Anyone tried this without a table and have it working?
There’s a problem in FF3: if i use mousewheel, i can scroll left and down and the white space occurs
If you just mousewheel scroll it, you would see white space all around.
Did you check that?
Nice work Chris, Full page backgrounds are something that I have always been intrigued by, but never really got my head around, due to different image dimensions, screen resolutions etc.
I was sort of under the impression that you would dynamically select a particular image depending on on the client browser size.
This looks pretty good though!
Hi Chris,
i only see “picture” placeholder text in Opera 9.64 on Vista Business 64 Bit. While Firefox shortly renders the page with a background picture and then redirects to your 404 error page…
Greetings
Mathew
Hi Guys,
I love this solution. It’s embed swf obviously. Any idea what’s the Action Script inside of .fla file looks like :) ?
it’s not flash. it’s javascript.
I may have missed it, but is anyone else having trouble displaying the bg image with IE7 or 8? It works beautifully in every other browser, but I get the broken image logo on IE. ugh! I’ve tried both techniques, by the way.
Massively impressed with this and it’s even better now that Doug has came up with a pure CSS solution!
Thank you for the great lesson. Yet, frankly I’m hesitate to apply the technique into my site. Sometimes I include table into DIV tag and the table jumped out of the main wrapper.
Very nice. I will try this on my next project.
Finally I found a good tutorial as well. Thanks
cool. adding this to my faves.
I had to tackle this problem myself recently and have come up with a fairly decent solution that is standards-compliant, uses minimal code (just one extra div), doesn’t use flash and seems to work in all browsers. Try this: http://blog.urbanmainframe.com/2009/05/create-a-dynamically-resizing-background-image-using-css/
Excellent! And what timing…
I saw the site a while back and wondered how they did it. Then I let it go since I couldn’t figure it out thru code!
Kudos for this article!
http://normalbookmark.com/ has a nice JS implementation of the full screen background.
I personally prefer using swf (flash) solution. swf file can be less than 15kb (compressed). I also checked flash samples that people posted above, all look perfect in all browser. Pure CSS solution is nice one, but probably it depends on your image and how big it is, and resizing it a bit tricky if you ask my opinion. In addition, with using flash, resizing is much better handled by flash (speaking from experiences)…http://www.beyondfayte.com is using flash background, yes the site is full flash, but notice the background how beautifully constructed and transitions. Now, image for sec., take that swf file, and implement your site (html and css)….
Nice effect though,Works nicely .
I saw this trick some time ago and also used it… it worked like a charm, but at the moment, using safari there is some problem. it doesn’t adapt in vertical. when the window is not “wide”, the photo doesn’t deform showing the white background here in the demo and the “loading” background on the credited site. But I remember that when I saw that site some time ago I didn’t noticed this problem.
Question – how do I get the best of both worlds? A scrolling page with a full static background. They showed one here – http://ringvemedia.com/introduction.
Hi Chris,
First of all, thanks for the great article.
I am using the Tecnique #2 and I’ve encountered some strange behavior when I started adding additional divs inside the content wrapper.
I don’t want to crowd this side with code but here is the page online
http://www.brentwoodrestaurant.com/bg_test.html
As you’ll see I am trying to put some distance between the divs using margins but when I apply a margin to a DIV that margin gets applied to the parent div for some reason.
I hope I was able to explain my problem and that you have a solution for it.
I am not sure if this is a bug with the script or my fault.
Thanks a lot in advance.
Never mind, I think it was entirely related to my nested divs, nothing to do with the script.
Interesting way of doing it. Seems to work well, thanks :-)
ok so how can we implement this into a wordpress theme?
can we get some help for wordpress users? no one ever talks about where to place this code and even if anyone is using under wordpress. any help is appreciated.
I think this is very well done though I do have a theory…
If you’re not adverse to marrying up your solution along with some php and javascript then you could use js to get the window height and width, then using Joe Lencioni’s Smart Image Resizer you could target your image thusly:
I would think you could actually resize the images as opposed to just scaling them and thus keep the download times at a minimum. Though this may only create the resized image on page load… and then the rest of your solution could scale it from there…
this is all just thinking aloud. I love Joe’s solution and use it all the time and think that you could incorporate it into this idea with great effect.
Supersized (http://buildinternet.com/project/supersized/) works very well and can be tweaked to allow for content with scroll.
Here is an example: SOUND Phuket http://www.soundphuket.com
Check the calendar page which has a scrollbar.
Yo, there is a mistake in your description!!
change it ffs. took me an hour figuring this out. I guess all the other people were taking the code from the demo site, where it was correct, that’s why nobody else noticed it. (Or maybe I just missed something in the beginning :P).
Anyways, in the description of the technique:
html, body, #bg, #bg table, #bg td {
height:100%;
width:100%;
overflow:hidden;
}
BUT! in the demo site:
html, body, #bg, #bg table, #bg td, #cont {
…
.
The missing things was the 100% height and width on the #cont. Without it the scrollnig did not function in any of browsers.
cheers.
For technique 1, there seems to be an issue in Opera 10 if you use the scroll wheel or keyboard arrows down.
Indeed, then you see white space you don’t want to be visible.
The solution is to add this to the CSS:
#bg { position: fixed; }
This works in all browsers.Nice post, I’m not a big 100% anything fan but this seems to work really well and might even try it out it in one of my site designs, so thanks for this.
Trying to figure out why the image will not show with DW? I even tested it out with EW3 and it works there…any ideas?
The div container that allows for content to be shown leaves a big white box in the middle of the page.
I’d like to request a further tutorial explaining in depth how to make all boxes of coding transparent to blend in with the image so that we may post whatever links and content we want into our respective websites.
A little extra info and we should be able to do virtually anything.
I’m very happy to find it, indeed. I’m photographer and sometimes I use to develop some photography websites, as former graphic designer.
Just a note that the technique #2 streches the image if we F11 the browser.
Thanks for sharing!
Ok I have one final issue to resolve on my website. How do I get the content box to make the paragraph tags separate.
My main page has a bunch of paragraph tags in it but they’re all bunched together instead of being spread out after being put into the content box.
I’m a little late catching on to this, but I love it! This changes my approach to design significantly. Thank you Chris.
This seems like a good solution, specially for clients who can be picky about what gets displayed to visitors. The only downside I can see here is the interpolation/resolution for larger monitors vs background file size. Great stuff. Thanks
Awesome stuff…!
It solved all my “oh no!-no-image-background” problems. :D
It helped me very well esp. for my computer project.
-thumbs up-
Thanks, great read. I find all technique, other then the CSS3, as partial and as short term solutions, semantically problematic, ans as mentioned above – performance challenged. I wouldn’t compromise on caching for this kind of a problem.
see my css3 solution implemented at stage-center.org
In CSS-Only Technique #2 right styles for image should be:
#bg img {
position:absolute;
top:25%;
left:25%;
right:25%;
bottom:25%;
margin:auto;
min-width:50%;
min-height:50%;
}
Note the 25% positioning it’s necessary in order to place image properly. That’s why the method fails in Opera. I didn’t tested it in other browsers yet.
But according to CSS 2.1 «Visual formatting model details» it’s a real bug that absolute positioned image aren’t centered with margin:auto.
Great post ..thanx yaaa
The new CSS3 method is awesome. It seems that I’m asked to do this technique on a little less than half my projects anymore. I think from now on I will do a combination of the CSS3 method with a fallback for older browsers using one of the other techniques.
Thanks Chris for another great post!
I’ve been exploring all kinds of non-flash fullscreen solutions for my designs. One thing I wanted to find is a cross browser solution which
a) Resized using the center for the image and not the top part
b) Was able to fade in on page load (with full ‘preloading’ control)
c) Used a minimum amount of code for fast page rendering.
Supersize was one of my first choice. But its JS was conflicting with other elements and I did not like the fact that the image could not fade in nicely all the time. Depending on what is was going on page load, there was no sure way to control the process.
I then found another approach which works as far as I can tell in all browsers, does not use JS or Flash and answered my requirements.
It’s a mix of CSS and the use of Tables. I know… it’s not ‘pure’, but it does the trick so well…
I was able to target the img with JQuery to have it fade in on page load exactly as I wanted – once the image was really ready for display – no room for error and no room for JQuery launching the fadein before the image had finished downloading.
I implemented it here : http://www.cadranhotel.com/.
Credits for this technique goes to : http://www.g2geogeske.com/ (which is where I first saw this concept and expanded from it).
This is my solution, a Dojo Toolkit module. If it is possible it uses CSS3, if not, falls back to JS.
http://code.ttcon.hu/fullscrn/
Wow, did not know about that CSS3 property, that will be amazing for the future.
I love how css3 is getting better and better…
thanks chris for the post
This is seriously awesome thanks! I’ll be attempting the ‘Awesome, Easy, Progressive CSS3 Way’. Can’t wait to try it ….
Thx! I used it now and works fine on http://optikaikeret.hu :)
(hungarian eyeglass etc. webshop)
Hey there,
Thanks for the awesome tip! :) I got it working on my up and coming site.
Got a quick question however, which probably isn’t the right place to post it but you never know: anyone have a solution to make these backgrounds random? I’m using a Joomla site atm and just want to cycle through the pictures every time somebody hits the page. I figured I can do it with some sort of jquery or better yet a PHP plugin, but would appreciate any advice.
Thanks!
Nice post, i love full screen backgrounds, and you give some quality ways to sort them! cheers
Thank you, I was looking to do this today. So awesome timing :P
Full screen backgrounds are really enjoyable if done well, excellent cross section of examples, have looked at Supersized in the past but we never implemented, although after all the positive comments about Supersized will look at implementing this in the future. LT
Here is a link to a website that I built using jQuery to mimic the look and function of a flash site.
http://www.aurumdesign.com
The background is a full screen background that swaps out via a nested div tag. It has been tested back to ie6 and works in most all browsers. Runs a little rough in older browsers due to some random jQuery functionality added per client request.
Awesome post, thanks for the tutorial and code. Greatly appreciated.
Hi, I really curious which of those techniques used at TouchArcade.com – I want to make my blog similar like that, with cool background image
I have to say I love it, but as always won’t work on IE 6 (extinc disonaur), I will have to say I would the jquery method well because I love javascript, thanks for the post, it helped :)
Great text, thanks for the help
Of course, you always have to be careful just how big that background photo will be. I usually try to keep them below 200kb to avoid having a larger page weight. A lot of times you have to sacrifice image quality for download speed when optimizing the jpeg.
Nice work, jQuery works fine on IE7 and FF3.6. But I can see the image before scaling.
Is there a possibility to load the image in background and when finished displaying? maybe smooth fading? I used jquery.html. Thanks!
Thank you!
CSS #2 worked like a charm – check it out: http://keaneangle.com/idosocial
But it has some positioning problems in ie7 & ie6..
Hi, is it possible to change the background image with javascript using the first method (only css) ?
i don’t know how to reach the html-tag.
the following does not work:
function changeBg(source){
document.html.background = source;
}
This is brilliant, no wonder you have so many posts, everyone ants to know how to do it. Thanks.
CSS-only #2 is amazing! I second @GreLI on his suggestion, even though this does not center the image it is still a nice IE7 fallback. I’d also suggest to include some image rendering properties for smoother results:
image-rendering: optimizeQuality; /* Gecko */
-ms-interpolation-mode: bicubic; /* IE */
Hi Chris, you might also want to check out the jQuery plugin fullscreenr I’ve just started using it on a project and it works great!
Hi Andy, I would like to share a jQuery plugin that does the same thing: http://srobbin.com/blog/jquery-plugins/jquery-backstretch/#demo
Chris, nice post!
Hey Chris, very nice, thanks for posting.
My web page has pink colored background screen image. But in this way will stand a very good picture. Thanks
Only the jQuery and CSS#1 work correctly in the latest Opera. CSS#2 fails as remarked in the article, and the neat CSS3 one works MOSTLY, but the background image experiences a shake (due to a delay in CSS processing, maybe?). With JS disabled things go BOOM with the jQuery method, leaving me with the CSS#1 the only option that works fine. Too bad…
My choice would probably be:
1. Use a default 1280px wide pic with CSS#1,
2. Add other pic versions (800px, 1920px, maybe more) and use jQuery to override the CSS#1 technique. In JS-disabled browsers, a 1280px wide image will probably look decent, in all other browsers there will be a perfect image with no (or as little as possible) upscaling while wasting as little bandwidth as possible.
Also remember that the images don’t need to be downscaled in many cases, sometimes it’s enough to show only a part of the image (as if cropped).
The approach I’m using on my company’s website is an image that fades to black near the borders (it doesn’t fill the entire page though, just the header). The pic is 1600px wide. Looks perfect on my 1440px wide screen, but I’ve also tested it on a 1920px wide one and it looks completely acceptable this way. I guess it all depends on the website design you have in mind though.
This was just what I needed for my latest project! My client will be very happy, thank you! <3
Thanks for this post. I had a client who needed a full page background, and I was able to do that thanks to this post.
This is interesting because I have a project at work where I need to do this function and was told to use this plugin called BgStretcher by ajaxblender.com.
It uses jquery but I wouldn’t mind trying to just use CSS 3 to accomplish the same goal.
Are there any downsides to using bgstretcher?
thank you so much for this
I’ve been fiddling around with my html for a VERY long time now and this finally got everything working
Thanks for this great article! If you don’t mind, it’s featured and linked on our blog (just an excerpt) :-)
it will look better if the image was gradient png and it covered with the same color of background-color
There’s a IE filter that can make this CSS3 trick work in any IE version:
http://cookbooks.adobe.com/post_Scale_Background_image_to_browser_size-17590.html
Too bad that that filter doesn’t preserve aspect ratio of the image.
Great article! I tried using the filter here, but when it’s applied all of the links on the page become disabled in IE8 (meaning, they appear but are not clickable). If I remove the filter code, all of the links become clickable again but obviously there isn’t a background anymore. Anyone had an issue with this and come up with a solution?
Chris, you are my hero. I want to be like you when and if I grow up!
visiting.. Nice info.. Cmon IE, be the best browser… Im so dissapointed with IE, there’re many bugs there.
Nice concept, like it!
Its works fine but in IE it shows some errors.
Hi there, I’m going to use the CSS3 option, and really want to make the background image a link, anyone know how I could achieve this?
Your first technique (css3) poses a problem.
I’m seeing a single pixel of white space to the left and right of the image, depending on window sizing.
Sometimes it’s there, sometimes it’s not.
Is there a cure?
Chris is a legend, personally I won’t argue one way or the other as long as a hack is straight-forward and productive. I applied this to my clients Joomla CSS with a great outcome. Generosity of the web community once again!
This is fantastic:
Is there any way to change the background on this element dynaically? – i.e.
<a>change bg</a>
That would be great! Any ideas?
EDITOR’S NOTE: Sure, with JavaScript you could watch for a click on that anchor link, select the HTML element, and apply different background. =)
sorry – html code for change bg in previous post reads onclick=”document.html.background …
Worked perfectly… just used the provided css and updated the images… thanks!
PS i used CSS option #2
check out here…
http://dsn.versusdsn.com
it doesn’t work in opera
the bg image is resized and located in the top left corner
Anybody have any idea of how I could lay an image on top of this that would scale and maintain its position as the background image scaled (like a marker on a map)?
That just amazing. Thanks alot for this. I will us it in some of my upcoming projects :)
Worked perfectly, nice tut.
Thanks.
This is all good info.
Being sort of new at this, any ideas how this site is made?
http://www.yabupushelberg.com
Thanks!
Is there a finite version for older versions of IE, or some special script I can implement to make the background wallpaper more stable?
Okay can somebody please help me?
I want to make this image:
http://t2.gstatic.com/images?q=tbn:ANd9GcRd66tQRZBspVVECmBHu4pMluIer0Zl6lhzcfd-75xlp-_kIus2
The background of my Tumblr page. http://connerftw.tumblr.com/
But it’s just tiled like 20 times. I want it to be one image as the entire background.
How do I do this? I can’t figure it out at all.
Hi there,
Thanks so much for the tutorial! I got it working but am having issues with the height cutting off on the iPhone.
Is there something I need to add for mobile devices? The index page is fine, but when I go to her blog page it cuts off and won’t let the viewer scroll down.
http://vanessafiola.com/blog
Best,
Katrina
the same problem has in ie6 and ie7. maybe overflow-y:scroll; for the body or html can solve the problem.. But you should hide this from other browsers..
This background image looks pretty nifty:
http://www.setupsigning.nl/diensten.html
Background image maintains a fixed ratio. Image is smootly resized.
How do I achieve this result??
i love uuuuuuuuuuuu!!
CSS Technique 2 works for me! But pity for IE 6 ( you know it still being used by many people out there )
CSS Technique 2 works for me. But pity on IE6 (you know it still being used by many people out there)
I’m getting an interesting effect in IE8+ using the “awesome, easy, progressive, CSS3 way.”
On a clients site, after applying the CSS, and the additional stuff supplied by adobe above to get IE to work properly….None of the links are clickable…
see here: …clients test site…
thoughts?
Thanks for this btw….Chris, your videos and article have launched me into a new career! I will be forever thankful. You do such an unselfish thing, teaching us, and I appreciate it.
Aaron
Update….
This issue is happening when using the ‘option #2’ solution as well…
I want to punch bill gates right now….lol
any ideas guys?
a
I now believe the problem lies with:
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader
So far I’ve tried adding:
hasLayout = ‘true’
and
different z-index values to the end of the alpha statement in the css….
like this:
-ms-filter: “progid:DXImageTransform.Microsoft.AlphaImageLoader(src=’/testSite/wp-content/themes/BareBones/images/bg3.png’, sizingMethod=’scale’, hasLayout = ‘true’)”
Seriously, I really am starting to loose steam with this problem….any constructive help or direction at all will be greatly appreciated.
a
I FIXED IT!!!!!!!!
added this to the header, ust after the body tag…:
changed the css to this:
I have the exact same problem as you, but I didn’t quite understand how you solved it. Do you have a site where you have used this method?
#bg_image{
position: absolute;
top:0;
left:0;
right:0;
bottom:0;
margin:auto;
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=’/testSite/wp-content/themes/BareBones/images/bg3.png’, sizingMethod=’scale’);}
min-width:100%;
min-height:100%;
html{
background: url(/testSite/wp-content/themes/BareBones/images/bg3.png) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover; }
Looks good only for proprietary hardware inside one of Microsoft ‘partner’ 1 million devices big corp installation. Never worked for me. Thanks for the wonderful cut and paste. Somewhere, eh…
Wow Chris this is awesome just what I’ve been looking for as my site jinks about a bit thanks very much
Hi guys,
nice tuts, thanx. I ran onto a problem and I would like to ask for help. I have a customer that would like to have a big picture for background but it shouldn’t scale. I will have a content in center and the background shouldn’t move if the resolution is lower as original. What I mean is that bg picture should always have the fix height, width, it should be centered and in case when the browser window width is lower as picture width, the picture should be cropped from both sides (left and right) not scaled. This way I will achieve that the content will have all the time the right background cover.
Is it possible to do that? Any help would be appreciated.
AB
Hi AB
Please excuse my poor english in advance…
Maybe this will help you :
I managed to ‘attach’ the image to the bottom with top:auto; bottom:0px
With min-height:640px and min-width:1024px for a 2560×1600 pic it fits almost any resolution/window size decently… *hiding*
Try top:0px;bottom:0px;left:auto;right:auto
Hope it will help :)
CSS Technique 2 works for me. Thank you so much.
jQuery Method is great for me!! Just perfect ;) thank you!!
CCS3 Way Rulz! Added in two mayor websites seems that they are working perfect!!!
Hey this is really the cleanest & simplest way for having a sweet ass background!
But I cant seem to get this workin in my DIV. It should be possible right?
My DIV has a fluid width and a fixed height of 200px.
I want the background image to always fit in width, maintain aspect ratio and center.
But how can I manage that with these codes?
I have the same question, if anyone finds a solution!
I have used the jquery method which worked just fine for me. I just love jquery, although css is “cleaner” maybe. Thank you for excellent post
I have a problem with the jQuery Method.. sometimes I need to refresh the page to see full size image..just SOMETIMES….There is, let’s say, a delay…anybody can help??
thank you!!
EDITOR’S NOTE: The above code is updated to fix this.
This works almost perfectly but there is a glitch that I can’t solve completly in big screens. I will describe it here and hopefully someone can confirm the glitch and see if there is any solution or if it is a glitch of the cover value in background-size property.
All works perfectly if there is no vertical scroll bar,
When there is a vertical scroll bar it appears that there is something like 1% of margin on the left side. When viewport is huge the gap starts to be bigger, if the viewport is smaller the gap disappears and works fine,
If instead of: “no-repeat center center fixed” I write: no-repeat 49% center fixed the left margin problem will be solved but it will appear 1% on the right which is better but still not perfect.
Conclusion:
I think the cover value is doing some aproximations and for some reason the output when there is a vertical bar is wrong at least in Chrome, Opera and Safari. Only Firefox and IE work fine.
“Awesome, Easy, Progressive CSS3 Way” worked for me! Thank you!
thanks for this grea tutorial, what are the image dimensions supposed to be ?
Watch out guys, there is a bug in Snap Mode in Windows 8 when you do this the CSS3 way.
[Here is a Dropbox link with screenshot of this.](https://www.dropbox.com/s/7je5f19vxp9bwxb/iebug.png “Here is a link with Dropbox screenshot of this.”)
Please, drop me a line if you have found a solution.
I used this on the body element to fix IE8 with a conditional css file.
IE8 is used throughout the company so it was essential it got dealt with tested also in IE Tester.
My mistake position fixed on body element didn’t work used this instead:
}
thank you , css3 way working for me!
Hi Chris… I interest with this topic. May be this is late… but I was try full screen background based on the tutorial. But adding some trick… below is my code
HTML
CSS
Jquery
$(window).load(function() {
var theWindow = $(window),
$bg = $(".home");
if(theWindow.width() != $bg.width())
{
$bg.css("width",theWindow.width());
}
if(theWindow.height() != $bg.height())
{
$bg.css("height",theWindow.height());
}
function resizeBg() {
if(theWindow.width() != $bg.width())
{
$bg.css("width",theWindow.width());
}
if(theWindow.height() != $bg.height())
{
$bg.css("height",theWindow.height());
}
}
console.log($bg.width() + " " + $bg.height());
console.log(theWindow.width() + " " + theWindow.height());
theWindow.resize(resizeBg).trigger("resize");
});
And I success to load it each time I change the browser scale. Thanks for your article.
Hey, what if there is 3 images for background. One on top, one on bottom and middle for repeat-y. I can not make it stretch on some shorter pages. You can see it on http://www.konji.rs , did it on some pages with plugin but it is a problem. Can do it with two: top and repeating one but with free no. Any suggestion? THX
I use this method a lot however I have implemented it on a clients site and she is using a windows phone to view her site and the background is not stretching.
I have tested on IOS and Android and all ok? any ideas?
Hi, how to make non full screen background (centered) but fixed.
I have a pure css3 (with SASS) sollution with retina support, IE Fallback AND it loads images depends on the Screen resolution:
HTML
SASS
mixins
SASS Style
Now you need 8 version of your background image:
For example this images are in the folder
/assets/images/background/
so your absolute path would beyourdomain.com/assets/images/background/_768.jpg
then you need this+fullscreen('/assets/images/background', '.jpg')
with the @media queri, it will load the image depends on the Screen Resolution and if its a Retina Display, it will load the Retina image (
double resolution)
Tested in Firefox 25, Chrome 31 and IE 7, 8, 9, 10
Credits to this article and retina.js for the
(-webkit-min-device-pixel-ratio : 1.5)
solutionOn line 4 you can find this:
$image_p : '../images/' + $image_path + '/'
this depends on your CSS location. in my solution the images are in
/assets/images/background/moon/
and the CSS
/assets/stylesheets/style.css
. so i need to add
../images/
to the $image_p and add the mixin with+fullscreen('background/moon', '.jpg')
This hase to be adjusted to your own location of your files
Thanks!
Hi Dino, that looks great.
Do you have any ideas as to how that might work on a one page website with multiple images as backgrounds?
Thanks,
Carlos
Hi, you can set the background image to a Class and change it with javascript. Use my code above and make something like this:
HTML
SASS
JQuery
It dosnt matter how you change the Class. Just set the fullscreen mixin to a Class and you can change it.
Thanks for the prompt response. Will give this a go later.
Thanking you! :)
Can anyone please tell me what is the minimum safest header background image size for a html/ wordpress theme? Is that 1600 px or less?
It really depends on your theme and any built-in limitations, but considering most users have screens that are at least 1280px wide these days then I would say that probably wouldn’t want to go much less than 1600px.
For full screen images or websites with full width images I always make them 1920×1280. I find its the best size to use across the board, looks good on a 15″ laptop but still looks good on a 27″ monitor.
Chris, two things happened just now, and we both hope your genius can figure this out, because we have enjoyed your background ‘cover’ method for years.
1) my desktop IE11 fails your ‘cover’ variable, apparently taking actual dimensions, and with liquid background image proportion fixed, and background size relative to windows size, shrinking background side edges inside windows edges, when window is not in correct proportion (whatever the windows size) to satisfy a set background-image proportions. You may be aware that Stu Nichols in England played with this OS sensitivity-thing using a white-rabbit image in 2002.
Dat bunny (today working better than ever before.
Abishek and the other Microsoft engineers watching my box’s window blocks may be interested, so we’ll give them a peek. Anyhoo… we suspect they know more than us.
2) Oh, and at the same time, using Safari, Chrome or IE, Mac or PC, your comments in this comment section overlap, so not readable, sadly.
2013 Christmas day W3C paradigm shift? Another global bug? Google/Microsoft combat blows? Localized (hopefully) web delivery issues mostly effecting (what else) IE?
Wasup, lol (lots of laughs).
I suggest imagecover.js plugin,it is awesome to cover an element with an image (it supports css2 and css3):
https://github.com/Metalchocobo/imagecover/
I’ve just added this to my css and works perfectly fine for me:
`{
margin:0;
padding:0;
}
/————————-
General Styles
————————–/
html{
/ This image will be displayed fullscreen /
background-image:url(images/bg1.jpg);
background-repeat:no-repeat;
background-position:center;
background-size:cover; / The Magic */
}`
When I am using CSS#1 some of my text goes under the image. How do I fix that?
I can see the text is under the image, because when I changed in the css top: 0px to top:60px suddenly text was revealed
nevermind, finxed by using z-index ;)
used second trick but now if i m writting anything on it doen appear.
like if i use
<
p> tag then it wont appear only image appears in the browser .
You need to add
#bg {z-index: -10}
or anything else lower than other elements you have on the page.#2 was by far the best solution, I’ve been trying several methods/ways and it was never nice especially with a bokeh image.
Thanks to Chris and Corey Worrell :)
I would like to keep the top of the image fixed (so it doesn’t disappear on wide screens), what method should I use and what changes (if any) should I make to the code? Thnx!
Not working. It does not resize the image.
Excellent resource. One thing I have found, though, is that older IEs (IE6 and 7) sometimes crash if you’re using filters excessively. Just something to be watchful for.
Thanks for the useful code snippets! I used the jQuery method, but modified it to keep the image centered at all times:
Is it possible to have a multiple full page images, that are background images?
For example, if you had a number of images in the HTML and you wanted each one to have the height and width of the browser and proportionate scaling in the same way that background-cover achieves, but also keep it in the document flow so you could scroll down the page as per usual.
So basically like the Technique number 2, but without fixed positioning on the parent?
Sorry, got it working. Just had to use absolute instead of fixed and have a relative parent to hold the flow.
Many mobile browser doesn’t support position fixed, though. So technique #1 might not be a good choice.
Hi, it’s work! Thank you.
Can i ask if is work on jquery mobile too? Website can, but is it same with mobile?
I use this >>>
body {
background-repeat: no-repeat;
background-attachment: scroll;
background-image: url(../image/mainbg.png);
max-height: auto;
max-width: 100%;
margin: 0px;
padding: 0px;
height: 800px;
background-position: 0px 0px;
width: 1280px;
}
so is this work on mobile apps too for the background?
thank you :)
for me this first option didnt work. using: background-attachment:fixed; made it work.
I tried using the css3 method on a block that had jquery and angular controlling it’s size. When I scrolled it out of view and then went back to the top of the page the background either disappeared or was split into sections. I modified the code below based on the Juliana Bicycles website and it works perfectly.
Really! Check out code source… We’ve come a long way. Why are you using script to replace default DOM standards?