如何在 Flexbox 对齐的侧边栏上模拟“位置:固定"行为 [英] How to simulate 'position:fixed' behavior on Flexbox-aligned sidebar
问题描述
因为已经有人回答了(我怎样才能有一个位置:固定;弹性盒大小元素的行为?)绝对/固定定位的盒子从弹性盒对齐元素的正常流中取出.但是我怎样才能至少模拟 position: fixed
行为,比如 width: 300px;高度:100vw
元素?
这是一个演示(http://codepen.io/anon/pen/ZGmmzR) 的初始布局,左侧边栏和右侧内容块.我希望 nav
像 position: fixed
元素一样跟随用户滚动页面.我知道如何在没有 Flexbox 的情况下做到这一点.首先,我会考虑不使用 JavaScript 的纯 CSS 解决方案.谢谢!
让容器 (.wrapper
) 与屏幕一样高,并且只在主 元素:
.wrapper {显示:弹性;高度:100vh;}部分 {弹性:1 1 自动;溢出:自动;}
http://codepen.io/Sphinxxxx/pen/WjwbEO
原答案:
您可以简单地将 <nav>
中的所有内容放在一个包装器中(此处:nav-wrapper
),然后修复该包装器:
<代码>....nav-包装器{位置:固定;顶部:0;左:0;}<nav role="导航"><div class="nav-wrapper">...
</nav>
http://codepen.io/anon/pen/PqXYGM
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?
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!
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 {
display: flex;
height: 100vh;
}
section {
flex: 1 1 auto;
overflow: auto;
}
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-wrapper {
position: fixed;
top: 0; left: 0;
}
<nav role="navigation">
<div class="nav-wrapper">
...
</div>
</nav>
http://codepen.io/anon/pen/PqXYGM
这篇关于如何在 Flexbox 对齐的侧边栏上模拟“位置:固定"行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!