元素的行为类似于位置粘性,但将其从文档流中取出?

问题描述 投票:0回答:2

这对我来说似乎很容易,但我似乎无法让它发挥作用,并且在网上找不到真正的解决方案。我有一个带有标题、一些内容和粘性导航栏的页面,该导航栏在小视口上显示为(折叠的)汉堡菜单。

基本上,我希望标题在向下滚动页面时消失,并且粘性导航栏/汉堡菜单在标题下方向上滚动,然后停留在页面顶部。汉堡菜单浮动到右侧(我使用 Flexbox、max-content 和 margin-left:auto 做到了这一点)。

现在,我想将粘性汉堡菜单从文档流程中取出,以便它与内容部分重叠。这就是我无法上班的原因。我不想使用position:fixed,因为汉堡菜单应该始终位于标题下方,而且我不能使用position:absolute,因为内容部分很长。

我尝试过使用 float:right,但是内容部分和汉堡菜单根本不重叠。我无法将 .sticky-navigation 放置在 .div.content 内,因为内容部分正在使用 display:grid,并且在网格在较小断点上的一列中对齐之前导航栏折叠到汉堡菜单(如汉堡菜单将占据一个网格项目,对吧?)。

我完全不知道如何才能实现这一目标。我不想使用 Javascript 来实现这一点,因为只用 CSS 就可以实现吗?另外,我担心性能会受到影响,尤其是在移动设备上。有人知道如何到达那里吗?

这是我的代码笔:https://codepen.io/alessandrov/pen/JjmaEgr

header {
  padding: 1rem;
  background: red;
}

.sticky-navigation {
  padding: 0.5rem;
  background: blue;
  position: sticky;
  display: flex;
  align-items: flex-end;
  justify-content: flex-end;
  max-width: 8rem;
  margin-left: auto;
  top: 1rem;
}

.content {
  background: green;
  padding: 1rem;
  padding-bottom: 15rem;
}

h1 {
  margin-bottom: 3rem;
}
<header>This is the header.</header>
<section class="content-section">
  <div class="sticky-navigation">
    <p class="burger">This is where the burger menu would go</p>
  </div>
  <div class="content">
    <h1>Big title</h1>
    <p>This is where all of the content would go. Repeated to simulate my page. This is where all of the content would go. Repeated to simulate my page. This is where all of the content would go. Repeated to simulate my page.
    </p>
 
</section>

html css
2个回答
1
投票

您已经接近使用

float:right
。您可以添加
shape-outside
,以便您的元素不会在流程中占据任何位置。
inset(50%)
将创建一个
0x0
矩形

header {
  padding: 1rem;
  background: red;
}

.sticky-navigation {
  padding: 0.5rem;
  background: blue;
  position: sticky;
  float: right;
  shape-outside: inset(50%);
  max-width: 8rem;
  margin-left: auto;
  top: 1rem;
}

.content {
  background: green;
  padding: 1rem;
  padding-bottom: 15rem;
}
<header>This is the header.</header>
<section class="content-section">
  <div class="sticky-navigation">
    <p class="burger">This is where the burger menu would go</p>
  </div>
  <div class="content">
    <h1>Big title</h1>
    <p>This is where all of the content would go. Repeated to simulate my page. This is where all of the content would go. Repeated to simulate my page. This is where all of the content would go. Repeated to simulate my page.
    </p>
 </div>
</section>


0
投票

对于任何正在寻找显示解决方案的人:应用网格/柔性,我发现将高度设置为 0 会使盒子完全脱离流程。

© www.soinside.com 2019 - 2024. All rights reserved.