twitter-bootstrap Bootstrap 4 固定顶部导航和固定侧边栏
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49641293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bootstrap 4 fixed top nav and fixed sidebar
提问by user3691644
This is a great example of how to create a navbar with a sidebar. Can anyone modify the code so that the top nav is top-fixed and the sidebar fixed/static with only the main page content scrolling? I can make the nav the nav top-fixed by assigning the class="fixed-top"to the nav, but I can't figure out how to make the sidebar fixed so that it remains in the same spot instead of scrolling up with the main page content. Applying class="sticky-top"to the sidebar doesn't seem to work.
这是如何创建带有侧边栏的导航栏的一个很好的例子。任何人都可以修改代码,以便顶部导航固定在顶部,侧边栏固定/静态,只有主页内容滚动?我可以让导航的导航顶部固定由分配class="fixed-top"到nav,但我无法弄清楚如何使侧边栏固定,使之保持在同一个地点,而不是与主网页内容滚动起来。应用于class="sticky-top"侧边栏似乎不起作用。
<nav class="navbar navbar-expand-md navbar-dark bg-primary fixed-top">
..
</nav>
<div class="row">
<div id="sidebar-container" class="sidebar-expanded d-none d-md-block">
<ul class="list-group sticky-top">
<li>Menu item..</li>
<li>Menu item..</li>
</ul>
</div>
<div class="col">
<!-- MAIN -->
</div>
</div>
回答by Zim
The sticky-topisworking, but it doesn't appear to be working for two reasons...
在sticky-top被工作,但它似乎没有奏效,原因有二...
- There isn't enough content in the main content area to scroll
- It's positioned at
top:0so it hides behind the fixed navbar
- 主内容区内容不足,无法滚动
- 它位于
top:0所以它隐藏在固定导航栏后面
Add CSS to offset the top of the sidebar (the same as height of fixed navbar).
添加 CSS 以偏移侧边栏的顶部(与固定导航栏的高度相同)。
.sticky-offset {
top: 56px;
}
<ul class="list-group sticky-top sticky-offset">..(sidebar)..</div>
And, then add enough content (or height) in the main area so that scrolling is necessary...
并且,然后在主区域添加足够的内容(或高度),以便滚动是必要的......
Working Demo:https://www.codeply.com/go/7XYosZ7VH5
工作演示:https : //www.codeply.com/go/7XYosZ7VH5
<nav class="navbar navbar-expand-md navbar-dark bg-primary fixed-top">
..
</nav>
<div class="row">
<div id="sidebar-container" class="sidebar-expanded col-2 d-none d-md-block">
<ul class="list-group sticky-top sticky-offset">
<li>Menu item..</li>
<li>Menu item..</li>
</ul>
</div>
<div class="col">
<!-- MAIN -->
</div>
</div>
回答by mate.gwozdz
There's a relatively new CSS position property called sticky.
有一个相对较新的 CSS 位置属性,称为sticky.
position: sticky;
top: 4em;
See how this works, what happens when you scroll to the end of the parent element. Leave height at auto. Reference - https://developer.mozilla.org/en-US/docs/Web/CSS/position
看看这是如何工作的,当您滚动到父元素的末尾时会发生什么。将高度保留在auto。参考 - https://developer.mozilla.org/en-US/docs/Web/CSS/position

