$(window).on("resize",function() { fullscreen() }); function fullscreen() { var f = $(".fullscreen-bg img"); var g = f.width() / f.height(); var e = $(window).width() / $(window).height(); if (g < e) { f.css({ width: $(window).width(), height: "auto", "margin-top": "-" + ((f.height() - $(window).height()) / 2) + "px" }) } else { f.css({ height: $(window).height(), width: "auto" }) } };