Html 如何在 Flexbox 对齐的侧边栏上模拟“位置:固定”行为
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31715240/
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
How to simulate 'position:fixed' behavior on Flexbox-aligned sidebar
提问by user3576508
As it was already answered (How can I have a position: fixed; behaviour for a flexbox sized element?) absolutely/fixed positioned boxes are taken out of the normal flow of Flexbox-aligned elements. But how can I at least simulate position: fixed
behavior of, say, width: 300px; height: 100vw
element?
正如已经回答的那样(我怎样才能有一个位置:固定;对于 flexbox 大小的元素的行为?)绝对/固定定位的框从 Flexbox 对齐元素的正常流中取出。但是我怎样才能至少模拟元素的position: fixed
行为width: 300px; height: 100vw
?
Here is a demo (http://codepen.io/anon/pen/ZGmmzR) of initial layout with sidebar on the left and content block on the right. I would like nav
act like position: fixed
element following user's scroll across the page. I know how to do it without Flexbox. In the first place I would consider pure CSS solution without using JavaScript. Thank you!
这是一个演示(http://codepen.io/anon/pen/ZGmmzR)的初始布局,左侧边栏和右侧内容块。我想在用户滚动页面后nav
像position: fixed
元素一样。我知道如何在没有 Flexbox 的情况下做到这一点。首先,我会考虑不使用 JavaScript 的纯 CSS 解决方案。谢谢!
回答by Sphinxxx
Edit:
编辑:
A solution that somehow feels less hacky could be to make the container (.wrapper
) as tall as the screen, and only add scrolling to the main <section>
element:
一种感觉不那么笨拙的解决方案可能是使容器 ( .wrapper
) 与屏幕一样高,并且只向主要<section>
元素添加滚动:
.wrapper {
display: flex;
height: 100vh;
}
section {
flex: 1 1 auto;
overflow: auto;
}
http://codepen.io/Sphinxxxx/pen/WjwbEO
http://codepen.io/Sphinxxxx/pen/WjwbEO
Original answer:
原答案:
You could simply put everything inside <nav>
in a wrapper (here: nav-wrapper
), and then fix that wrapper:
您可以简单地将所有内容放在<nav>
包装器中(此处:)nav-wrapper
,然后修复该包装器:
...
.nav-wrapper {
position: fixed;
top: 0; left: 0;
}
<nav role="navigation">
<div class="nav-wrapper">
...
</div>
</nav>