我试图同时实现两种样式,一种包括粘滞位置,另一种包括粘滞元素的父元素:
- 我想我的网页的第一部分,让我们称之为"英雄节",采取整个屏幕的高度(这部分有一个
bottom
元素,应该在屏幕的底部,当页面滚动到顶部,其余的内容应该遵循后) - 我也希望导航栏粘在网站的顶部,但这个导航栏不是在网站的开头(当页面滚动到顶部时),它在第二个位置,就在标题之后
另外,我试图找到一个不使用JavaScript的解决方案,css only.
以下是一段代码片段,其中包含两列,一列表示问题的两个方面:
body {
margin: 0px 10px;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
font-size: 10px;
}
.hero_bottom {
height: 50px;
background-color: lightblue;
margin: 10px 0px;
}
main {
height: 200vh;
background-image: linear-gradient(red, yellow);
}
section.left header {
display: grid;
grid-template-rows: 1fr 1fr auto;
gap: 10px;
height: 100vh;
border: 1px solid blue;
}
nav {
position: sticky;
top: 0px;
}
<section class="left">
<!-- HERO SECTION -->
<header>
<h1>
either I have the "bottom" element at the bottom of the screen view...
</h1>
<nav>
<a href="#">link</a>
<a href="#">link</a>
<a href="#">link</a>
</nav>
<div class="hero_bottom">hero-bottom</div>
</header>
<!-- end HERO SECTION -->
<main>main content</main>
</section>
<section class="right">
<!-- HERO SECTION -->
<h1>
...or I have the navbar that stick through the entire website. But how to have both ?
</h1>
<nav>
<a href="#">link</a>
<a href="#">link</a>
<a href="#">link</a>
</nav>
<div class="hero_bottom">hero-bottom</div>
<!-- end HERO SECTION -->
<main>main content</main>
</section>
如果navbar是body的直接子元素(或者任何具有网站高度的元素,如我的示例中的<section>
),那么很容易使navbar贯穿整个网站,如果页面顶部出现的所有内容都在块级包装器中,那么很容易将hero-bottom
元素放置在hero部分的底部,包括navbar.
但是一个阻止了另一个:底层元素需要块级包装器,而包装器防止导航栏贯穿整个网站.那是我的问题!
我不觉得有一个解决方案,使导航栏粘到它的祖父(在这种情况下,因为我知道这有时是可能的,如果你可以使父内联级别例如),所以也许它是更好地找到一个解决方案,有bottom
元素在底部的英雄节没有包装?