Search code examples
jquerycssclippingclip

Making CSS clip rect responsive


I'm trying to implement a little something here: http://atmapp.io/beta/

I'm clipping a Google Maps object, to fit in the phone area. It works great on 1920x1080 (mainly because I hardcoded the rect's values). How can I make the clip: rect responsive?

I've tried with jQuery, but I'm an idiot, and I'm probably miles off:

CSS

#map-canvas2 {
  width:100%;
  height: 100%;
  position: absolute;
  z-index: 9999;
  bottom: 0;
  clip:rect(191px, 1579px, 732px, 1275px);
}

jQuery

var oldresX = 1920;
var oldresY = 943;
var rectTop = 191;
var rectRight = 1579;
var rectBottom = 732;
var rectLeft = 1275;
var newRectTop;
var newRectRight;
var newRectBottom;
var newRectLeft;

var newResX;
var newResY;


$(window).resize(function(){
    newResY = oldresY - window.innerHeight;
    newResX = oldresX - window.innerWidth;

    newRectTop = rectTop + newResY;
    newRectRight = rectRight - newResX;
    newRectBottom = rectBottom - newResY;
    newRectLeft = rectLeft + newResX;

    //alert(newResX + "x" + newResY);
    $("#map-canvas2").css('clip', 'rect('+newRectTop +'px, '+newRectRight +'px, '+newRectBottom +'px, '+ newRectLeft+'px)');
    //alert('rect('+newRectTop +'px, '+newRectRight +'px, '+newRectBottom +'px, '+ newRectLeft+'px)');
});

EDIT

For those wondering, this is how the map is supposed to "fit": enter image description here


Solution

  • Use clip-path with inset basic shape instead of deprecated clip.
    Don't forget about -webkit prefix.

    html, body {
      width: 100%;
      height: 100%;
      overflow: hidden;
    }
    
    body {
      margin: -1px;
      border: 1px solid transparent;
    }
    
    section {
      margin: 1em;
      width: 50%;
      height: 50%;
      border: 1px dotted blue;
    }
      
    div {
      width: 100%;
      height: 100%;
      background: red;
      -webkit-clip-path: inset(50% 0 4px 1em);
      clip-path: inset(50% 0 4px 1em);
    }
    <section><div></div></section>