There are several techniques for getting an image to occupy the full width and height of the screen. Each technique is considered appropriate for a given scenario as we can handle the problem via JavaScript, CSS or server side.
In this answer solutions make use of JavaScript with jQuery feature.
jQuery
This plugin works the way that you indicate in the question, ie it makes use of several images loading the most appropriate according to the width of the screen:
(function() {
var win = $(window);
win.resize(function() {
var win_w = win.width(),
win_h = win.height(),
$bg = $("#bg");
// Carregar imagem de fundo mais estreita com base na
// largura do ecrã, mas nunca carregar nada mais estreito
// do que o que já está carregado, se alguma coisa estiver.
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;
}
}
// Definir a nova imagem
$bg.attr('src', '/img/bg/' + chosen + '.jpg');
// para testar...
// console.log('Chosen background: ' + chosen);
}
// Determinar se a largura ou a altura deve ser de 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);
Code removed from the CSS-Tricks website in this article:
Perfect Full Page Background Image | CSS-Tricks
Very easy to use, it allows us to transform a simple <img/>
into an image to occupy 100% X 100% of the screen, as well as to indicate the image in the PlugIn :
Include Script after adding jQuery :
<script type="text/javascript" src="/vegas/jquery.vegas.js"></script>
Include CSS :
<link rel="stylesheet" type="text/css" href="/vegas/jquery.vegas.css" />
Start PlugIn :
$(function() {
$.vegas({
src:'/images/background.jpg'
});
});
Vegas - Demo