问题
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