Search code examples
htmlcsscss-transformssticky

HTML / CSS - Position Sticky and transform without resizing viewport


In my website, I have elements that use transformations. I have noticed that these transformations resize the viewport. Normally I would solve this by giving the html and body overflow-x: hidden but then my header with position: sticky doesn't work.

How can I prevent the transformed elements from resizing the viewport and keep using position: sticky?

I have added an example below.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.scale {
  padding: 100px;
  width: 100%;
  height: 400px;
  background-color: green;
  transform: scale(2);
  position: relative;
  z-index 1;
}

header {
  position: sticky;
  position: -webkit-sticky;
  top: 0;
  left 0;
  right 0;
  height: 50px;
  background-color: red;
  z-index: 2;
}
<header>I want this header to remain sticky</header>
<div class="scale">
But I don't want this div to resize the x-axis of the viewport.
</div>


Solution

  • Use another container where you can apply overflow:hidden

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    .scale {
      padding: 100px;
      width: 100%;
      height: 400px;
      background-color: green;
      transform: scale(2);
      position: relative;
      z-index 1;
    }
    
    .container {
      overflow: hidden;
    }
    
    header {
      position: sticky;
      position: -webkit-sticky;
      top: 0;
      left 0;
      right 0;
      height: 50px;
      background-color: red;
      z-index: 2;
    }
    <header>I want this header to remain sticky</header>
    <div class="container">
      <div class="scale">
        But I don't want this div to resize the x-axis of the viewport.
      </div>
    </div>