Search code examples
javascriptcssfullscreen

Fullscreen image with border that shrinks depending by device resolution


Hello everybody I want to make a homepage with a fullscreen image on the background with a border all around.

I have been able to do it as you can see from this jsfiddle

https://jsfiddle.net/dforce/3j5uo5qo/1/

but I would like that the border shrinks when the resolution is smaller or desappear on resolution is smaller than 979px.

I use this script to make the border:

    <script>
$theBorder=35; //border around image (change top and left values of #bg accordingly)
$bg=$("#bg");

$bgimg=$("#bg #bgimg");

$preloader=$("#preloader");
//]]> 

$(window).load(function() {
    FullScreenBackground($bgimg,$bg);

    $(window).resize(function() {
        FullScreenBackground($bgimg,$bg);
    });
});

$bgimg.load(function() {
    var $this=$(this);
    FullScreenBackground($this,$bg);
    $preloader.fadeOut("fast");
    $this.delay(200).fadeIn("slow");
});

function FullScreenBackground(theItem,theContainer){
    var winWidth=$(window).width();
    var winHeight=$(window).height();
    var imageWidth=$(theItem).width();
    var imageHeight=$(theItem).height();
    var picHeight = imageHeight / imageWidth;
    var picWidth = imageWidth / imageHeight;
    if ((winHeight / winWidth) < picHeight) {
        $(theItem).css("width",winWidth);
        $(theItem).css("height",picHeight*winWidth);
    } else {
        $(theItem).css("height",winHeight);
        $(theItem).css("width",picWidth*winHeight);
    };
    $(theContainer).css("width",winWidth-($theBorder*2));
    $(theContainer).css("height",winHeight-($theBorder*2));
    $(theItem).css("margin-left",(winWidth- $(theItem).width())/2);
    $(theItem).css("margin-top",(winHeight- $(theItem).height())/2);
}
</script>

Thank you for your help!


Solution

  • What about responsive css?

    Something like

    <div id="mainimage">
        <div class="img"></div>
    </div>
    

    and the css:

    body{
      margin:0;
      padding:0;
      background:#fff;
    }
    
    #mainimage {
      box-sizing: border-box;
      width: 100%;
      height: 300px;
      padding: 20px;
    }
    
    @media(max-width: 1300px) {
      #mainimage{
        padding: 10px;
      }
    }
    @media(max-width: 979px) {
      #mainimage{
        padding: 0px;
      }
    }
    .img{
      height:100%;
      width: 100%;
      background: url(http://www.piedicosta.com/jnuovo/images/big.jpg) no-repeat center center; 
      background-size: cover;
    }
    

    You can add transitions to make the change smoother, something like

    #mainimage {
      -webkit-transition: all 0.50s ease-in-out;
      -moz-transition: all 0.50s ease-in-out;
      -ms-transition: all 0.50s ease-in-out;
      -o-transition: all 0.50s ease-in-out;
    }