Search code examples
csscss-grid

Prevent grid area size increase / decrease when user zooms browser


I have a layout which has decorative borders ( top, right, bottom, left ), these borders do not contain content, but do contain ornate SVG patterns.

These borders are being defined using the grid-template-columns and grid-template-rows grid properties, and have a height or width of 70px.

When a user sets their browser zoom level to 125%, 150%, 200% the size of the element scales proportionately ( 87px, 105px, 140px )

How do I prevent some grid areas ( top, right, bottom, left ) from growing / shrinking based on user's browser zoom input.

.stage-inner {
  min-height: 100vh;
  display: grid;
  grid-template-columns: 70px 1fr 1fr 1fr 70px;
  grid-template-rows: 70px 1fr 1fr 1fr 70px;
  grid-template-areas:
    "top top top top top"
    "left content content content right"
    "left content content content right"
    "left content content content right"
    "bottom bottom bottom bottom bottom";
}

https://codepen.io/MathiasaurusRex/pen/bzBdmX


Solution

  • You can try accessing the device pixel ratio and divide your dimension by that percentage to recalculate a dimension that will render at 70px.

    browserZoomLevel = Math.round(window.devicePixelRatio * 100);
    

    https://codepen.io/Jason_B/pen/GzNZZd

    I forked your codepen and added this jQuery code:

    $( window ).on( 'load resize', function() {
        const browserZoomLevel = Math.round(window.devicePixelRatio * 100);
        const normalizedDimension = 70 * 100 / browserZoomLevel + 'px';
    
        $( '.stage-inner' )
            .css( 
                'gridTemplateColumns', 
                normalizedDimension + ' 1fr 1fr 1fr ' + normalizedDimension 
            ).css(
               'gridTemplateRows', 
                normalizedDimension + ' 1fr 1fr 1fr ' + normalizedDimension 
        );
    });