3

I have a button fixed inside of outer div. The problem is when I set position: fixed(to keep the button stay while the page is scrolling) it didn't work properly.

The button still scrolled and moved out of the screen.

here is my code

.rotate {
  transform: rotate(30deg);
  background: blue;
  width: 300px;
  height: 300px;
  margin: 0 auto;
}

.fixed {
  position: fixed;
  background: red;
  padding: 10px;
  color: white;
  top: 50px;
}
<div class="rotate">
  <button class="fixed"> I am fixed inside a rotated div.</button>
</div>
<!--   <div class="fixed"> I am fixed outside a rotated div.</div> -->

How can I fix it to keep button always display on the screen while scrolling the page?

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
DinhNgocHien
  • 707
  • 3
  • 17
  • 34
  • 1
    this is due to the rotation. You may apply the rotation to the button instead – Temani Afif Oct 11 '17 at 17:02
  • @TemaniAfif I see, can it be fixed regardless the rotation or not? – DinhNgocHien Oct 11 '17 at 17:06
  • i don't know how to explain this, but it's seems that the rotation break the position property. The only solution i see it to make the transform to the inner elements and not outer elements ... but maybe more experienced people will give you a better one :) – Temani Afif Oct 11 '17 at 17:10
  • View it https://stackoverflow.com/questions/2637058/positions-fixed-doesnt-work-when-using-webkit-transform – Hiren Vaghasiya Oct 11 '17 at 17:11

2 Answers2

4

This is either a buggy or by design behavior by the browsers: basically, and "position: fixed" fixed element won't be fixed if any parent element has "transform" set. The following thread has some reference on it:

Positions fixed doesn't work when using -webkit-transform

As for a workaround, you might use a as a wrapper and nest the colored and the rotated inside it, then adjust the positioning with "margin". It's kinda hacky, but it might work depending on the situation. Here's a demo:

[http://codepen.io/jean-andreghetto/pen/OxEaVN?editors=1100][2]
jean377
  • 86
  • 5
2

You have the fixed element inside of the static box, which means you made the red link fixed to the blue box, and not to the outside. What you need to do is remove the red link of inside the blue box.

This should be what you want.

https://codepen.io/dawsonhudson17/pen/jGKeRy

.rotate {
  transform: rotate(30deg);
  background: blue;
  width: 300px;
  height: 300px;
  margin: 0 auto;
}
.fixed {
  position: fixed;
  background: red;
  padding: 10px;
  color: white;
  top: 50px;
  left: 50%;
  z-index: 2;
  transform: translate(-50%) rotate(30deg);
  display: block;
  }

  <button class="fixed"> I am fixed inside a rotated div.</button>

  <div class="rotate">
  </div>