【问题标题】:Position sticky does not remain centrally aligned upon screen resize屏幕调整大小时,置顶位置不会保持居中对齐
【发布时间】:2021-10-08 18:38:41
【问题描述】:

我注意到,在屏幕宽度减少一定程度后,居中对齐(垂直)具有粘性的元素会开始崩溃,具体取决于该元素的宽度。与 position: fixed 不同,粘性元素最终会卡住并失去其中心对齐方式。

知道为什么会发生这种情况以及解决方法吗?

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

【问题讨论】:

  • 不要使用 left 和 transform 属性来居中 div 尝试使用 display flex 和 margin auto 然后看看会发生什么也尝试将 width 属性更改为 max-width

标签: html css sticky


【解决方案1】:

您可以在父类上使用 flex 并使用 justify-content 来做到这一点

示例: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>

【讨论】:

    猜你喜欢
    • 2020-07-18
    • 2016-08-17
    • 2016-04-20
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    • 2016-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多