How To Get A Background Image To Reveal More Or Less When You Scroll
This post was originally published on August 21, 2009 and is now updated equally it has been entirely revised. Both original methods are removed and now replaced past four new methods.
The goal here is a groundwork image on a website that covers the entire browser window at all times. Let'southward put some specifics on it:
- Fills unabridged page with image, no white space
- Scales image as needed
- Retains image proportions (aspect ratio)
- Epitome is centered on page
- Does non cause scrollbars
- Equally cross-browser compatible as possible
- Isn't some fancy shenanigans like Flash
Image above credited to this site.
Awesome, Easy, Progressive CSS3 Way
We can practice this purely through CSS thanks to the groundwork-size
belongings at present in CSS3. We'll use the html
element (better than torso
as it's always at least the height of the browser window). We set up a fixed and centered background on information technology, so adjust it's size using background-size
set to the cover keyword.
html { background: url(images/bg.jpg) no-repeat centre eye fixed; -webkit-groundwork-size: embrace; -moz-groundwork-size: encompass; -o-groundwork-size: cover; groundwork-size: comprehend; }
Works in:
- Safari 3+
- Chrome Whatever+
- IE 9+
- Opera 10+ (Opera 9.v supported background-size only not the keywords)
- Firefox iii.6+ (Firefox four supports non-vendor prefixed version)
View Demo
Update: Thanks to Goltzman in the comments for pointing out an Adobe Developer Connection article which features some code to make IE exercise cover backgrounds too:
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";
Simply 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 employ the in a higher place IE filters and having bug with scrollbars or dead links or any else (like Pierre above) should try NOT using them on the html
or body
chemical element. But instead a fixed position div with 100% width and height.
CSS-Only Technique #1
Large thanks, as usual, to Doug Neiner for this alternate version. Here we apply an inline <img>
element, which will be able to resize in any browser. We ready a min-elevation
which keeps it filling the browser window vertically, and set a 100% width
which keeps it filling horizontally. We also prepare a min-width
of the width of the epitome and then that the image never gets smaller than it actually is.
The peculiarly clever bit is using a media query to check if the browser window is smaller than the image, and using a combo pct-left and negative left margin to continue it centered regardless.
Here is the CSS:
img.bg { /* Set rules to make full background */ min-superlative: 100%; min-width: 1024px; /* Set proportionate scaling */ width: 100%; height: auto; /* Set upward positioning */ position: stock-still; 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 skilful browsers: Safari / Chrome / Opera / Firefox
- IE half dozen: Borked – but probably fixable if y'all use some kind of stock-still positioning shim
- IE 7/8: Mostly works, doesn't centre at minor sizes just fills screen fine
- IE 9: Works
View Demo
CSS-Only Technique #2
One rather elementary way to handle this is to put an inline epitome on the page, fixed position information technology to the upper left, and give it a min-width and min-summit of 100%, preserving it's aspect ratio.
<img src="images/bg.jpg" id="bg" alt="">
#bg { position: fixed; superlative: 0; left: 0; /* Preserve aspet ratio */ min-width: 100%; min-height: 100%; }
Even so, this doesn't center the paradigm and that's a pretty mutual desire here… And then, we tin ready that by wrapping the paradigm in a div. That div we'll make twice every bit big as the browser window. So the image will exist placed, still preserving it'southward aspect ratio and covering the visible browser window, and the dead centre of that.
<div id="bg"> <img src="images/bg.jpg" alt=""> </div>
#bg { position: stock-still; top: -fifty%; left: -50%; width: 200%; height: 200%; } #bg img { position: absolute; tiptop: 0; left: 0; right: 0; bottom: 0; margin: auto; min-width: 50%; min-superlative: 50%; }
Credit to Corey Worrell for the concept on this i.
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 manner (wrongly positioned, non sure why)
- Peter VanWylen wrote in to say that if you add the image via JavaScript, the img needs to have width: auto; and acme: car; to work in IE 8, 9, or 10.
View Demo
Update January 2018: Trying to get this to work on Android? JL García wrote to me proverb he needed to add together tiptop: 100%; and overflow: hidden; to the html chemical element to become it to work. The full snippet existence:
html { background: url(images/bg.jpg) no-repeat centre center fixed; groundwork-size: encompass; height: 100%; overflow: subconscious; }
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 attribute ratio of the image (inline <img>
we intend to use equally a background) is larger or smaller than the electric current aspect ratio of the browser window. If information technology is lower, than we can set only the width
to 100% on the image and know it will make full both height and width. If information technology is higher, nosotros can set only the height
to 100% and know that information technology will fill both the height and width.
Nosotros accept access to this information through JavaScript. As usual effectually hither, I like to lean on jQuery.
<img src="images/bg.jpg" id="bg" alt="">
#bg { position: fixed; top: 0; left: 0; } .bgwidth { width: 100%; } .bgheight { acme: 100%; }
$(window).load(part() { 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 y'all could definitely change this to do that. Credits to Koen Haarbosch for the concept backside this idea.
Works in:
- IE7+ (could probably make it IE6 with a fixed position shim)
- Most any other desktop browser
View Demo
Update (June 2012): Reader Craig Manley writes in with a technique to load an appropriately sized groundwork image according to screen. As in, don't load some huge 1900px broad groundwork epitome for an iPhone.
First, you'd brand images like 1024.jpg, 1280.jpg, 1366.jpg, etc. Then instead of loading an img, yous'd load a shim.
<img id="bg" src="data:epitome/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" alt="" style="position: fixed; left: 0; top: 0" />
If y'all don't similar the gif shim (personally I think it's OK because information technology's not "content" it'south a background) y'all could load up one of the real images instead. This code will account for that.
So 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 prototype based on // viewport width, but never load annihilation narrower // that what's already loaded if anything. var available = [ 1024, 1280, 1366, 1400, 1680, 1920, 2560, 3840, 4860 ]; var electric current = $bg.attr('src').match(/([0-nine]+)/) ? RegExp.$ane : nil; if (!current || ((electric current < win_w) && (current < bachelor[available.length - 1]))) { var chosen = available[available.length - 1]; for (var i=0; i<bachelor.length; i++) { if (bachelor[i] >= win_w) { chosen = available[i]; intermission; } } // Set the new epitome $bg.attr('src', '/img/bg/' + called + '.jpg'); // for testing... // console.log('Chosen background: ' + called); } // Determine whether width or summit should be 100% if ((win_w / win_h) < ($bg.width() / $bg.height())) { $bg.css({height: '100%', width: 'motorcar'}); } else { $bg.css({width: '100%', height: 'auto'}); } }).resize(); })(jQuery);
Annotation that screen width isn't the only possible good data to have when choosing an image size. Run into this commodity.
Savor
If you use this, please experience free to get out what technique you used and if you altered it in whatsoever fashion in the comments beneath. E'er cool to come across techniques "in the wild."
Download Files
Just for posterity's sake, there is another example in here called table.php which uses an old technique that used to exist a role of this commodity. It had some cleverness, just wasn't quite equally good as either CSS technique now presented higher up.
Other Resources
- jQuery plugin: Vegas, past Jay Salvat
How To Get A Background Image To Reveal More Or Less When You Scroll,
Source: https://css-tricks.com/perfect-full-page-background-image/
Posted by: matterfinge1992.blogspot.com
0 Response to "How To Get A Background Image To Reveal More Or Less When You Scroll"
Post a Comment