Home > Net >  Position sticky does not remain centrally aligned upon screen resize
Position sticky does not remain centrally aligned upon screen resize

Time:10-08

I've noticed that centrally aligning (vertically) an element with position sticky starts to break down after a certain reduction of screen width, depending on that elements width. Unlike position: fixed, the sticky element eventually gets stuck and loses its central alignment.

Any idea why this is happening and a workaround?

div {
  height: 100px;
  width: 500px;
  background-color: red;
  position: sticky;
  left: 50%;
  transform: translateX(-50%);
}
<div>
</div>

CodePudding user response:

You can do it with using flex on parent class and using justify-content

Example: https://jsfiddle.net/9cp6borj/

<body>
  <div class="div__item">
    <div class="div__sticky">
    </div>
  </div>
</body>
<style>
.div__item {
  display:flex;
  justify-content:center;
}
.div__sticky {
  height: 100px;
  width: 500px;
  background-color: red;
  position: -webkit-sticky;
  position: sticky;
  top: 20px;
}
</style>

CodePudding user response:

Another way to position the div element to not mess it up. Without adding new elements.

div {
  height: 100px;
  width: 500px;
  background-color: red;
  position: sticky;
  left:0;
  right:0;
  margin:auto;
}
<div>
</div>

  • Related