position: sticky, works in Chrome but not in Firefox

流过昼夜 提交于 2021-01-05 10:42:54

问题


I need to have a vertical parent-height div which contains smaller divs. In case there's extra space, all but the last divs should be placed on top, and the latest div should be placed at the bottom. I've implemented it with Bootstrap and flex.

Now I thought that it would be nice if, when possible, the bottom div will be at the bottom of the viewport instead of at the bottom of the containing div. I've implemented it with position: sticky, and it works on Chrome but not in Firefox (both should support position: sticky).

My code:

<div id="container" class="d-flex flex-column">
    <div class="flex-item">1</div>
    <div class="flex-item">2</div>
    <div class="d-flex flex-column last">
      <div class="flex-item mt-auto last-inner">3</div>
    </div>
</div>

CSS:

#container {
    height: 1000px;
}

#container .last {
    flex: 1;
}

#container .last-inner {
    position: sticky;
    bottom: 0;
}

JSFiddle


回答1:


sticky seems to be tricky and not yet implemented the same way everywhere.

I usually trust FF on this behavior, chrome add issues with sticky and removed it a couple of times the past 3 years, i'm glad it is avalaible again and for month in chrome.

For FF, the sticky element has to be a direct child of #container, else, it will stick at bottom 0 of .last being a flex child. being a flex child, it becomes the first parent reference for the coordonate bottom:0 instead body. #container has obviously no formatting context and html can be the reference.

#container {
  height: 1000px;
}

#container .last {
  flex: 1;
}

#container .last-inner {
  position: sticky;
  bottom: 0;
}

.flex-item {
  background: tomato;
  padding: 5px;
  width: 200px;
  height: 50px;
  margin-top: 10px;
  line-height: 50px;
  color: white;
  font-weight: bold;
  font-size: 2em;
  text-align: center;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div id="container" class="d-flex flex-column">
  <div class="flex-item">1</div>
  <div class="flex-item">2</div>
  <div class="d-flex flex-column last">
  </div>
  <div class="flex-item mt-auto last-inner">3</div>
</div>


来源:https://stackoverflow.com/questions/52137323/position-sticky-works-in-chrome-but-not-in-firefox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!