There are several techniques for getting an image to occupy the full width and height of the screen. Each technique is considered suitable for a particular scenario because we can handle the problem via Javascript, CSS or on the server side.
In this answer the solutions make use of Javascript with jQuery.
jQuery
This Plugin works the way you indicate in the question, IE, it makes use of several images loading the most suitable depending on 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 taken from the CSS-Tricks website in this article:
Perfect Full Page Background Image | CSS-Tricks
Very easy to use, allows us to transform a simple <img/>
an image occupying 100% X 100% of the screen, and specify the image on the screen Plugin:
Include the Script after the inclusion of jQuery:
<script type="text/javascript" src="/vegas/jquery.vegas.js"></script>
Include the CSS:
<link rel="stylesheet" type="text/css" href="/vegas/jquery.vegas.css" />
Start the Plugin:
$(function() {
$.vegas({
src:'/images/background.jpg'
});
});
Vegas - Demo
background image 100% you don’t need js, it’s only by width and height 100%. But about what you said about adapting according to the resolution, you can use media queries...
– HiHello