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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:51:43  来源:igfitidea点击:

How to simulate 'position:fixed' behavior on Flexbox-aligned sidebar

htmlcsslayoutweb-deploymentflexbox

提问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: fixedbehavior of, say, width: 300px; height: 100vwelement?

正如已经回答的那样(我怎样才能有一个位置:固定;对于 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 navact like position: fixedelement 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)的初始布局,左侧边栏和右侧内容块。我想在用户滚动页面后navposition: 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>

http://codepen.io/anon/pen/PqXYGM

http://codepen.io/anon/pen/PqXYGM