使右下角的固定元素上升到页脚上方
Make a bottom right fixed element rise above footer
我想知道如何让固定在屏幕右下角的 div 在页面到达页脚后变得不固定。
例如,如果我的 html 是:
<div class="main" />
<div class="fixed" />
<div class="footer" />
而我的 css 是:
.main {
height: 100vh;
background-color: aqua;
width: 100vw;
}
.fixed {
background-color: green;
height: 200px;
position: fixed;
bottom: 0px;
width: 200px;
}
.footer {
background-color: brown;
height: 300px;
width: 100vw;
}
我想将我的 div 固定在底部,直到页脚开始显示,然后让它在页脚顶部滚动。我应该使用粘性定位吗?如果是这样,我该怎么做?如果没有,是否有更好的解决方案?
谢谢
您可以使用 position: sticky
和 bottom: 0
将其粘贴到视口底部(回答您的 如何 的问题)。由于它的非粘性位置就在页脚之前,当视口到达那里时它会自然地停留。
body {
font-weight: bold;
font-size: 24px;
padding-bottom: 300px;
}
main * {
padding: 10px;
background-color: #ccc;
border: 1px solid #000;
}
.content {
min-height: 1000px;
}
.sticky {
position: sticky;
/* the important part - stick to the bottom */
bottom: 0;
border: 1px solid red;
background-color: white;
}
<main>
<div class="content">content</div>
<div class="sticky">I'm sticky</div>
<footer>footer</footer>
</main>
话虽这么说,正如 Will 在评论中提到的那样 - 你应该使用它吗?这取决于您支持的浏览器。如果您需要支持旧版浏览器,则需要后备 and/or JavaScript 来处理定位。
我想知道如何让固定在屏幕右下角的 div 在页面到达页脚后变得不固定。
例如,如果我的 html 是:
<div class="main" />
<div class="fixed" />
<div class="footer" />
而我的 css 是:
.main {
height: 100vh;
background-color: aqua;
width: 100vw;
}
.fixed {
background-color: green;
height: 200px;
position: fixed;
bottom: 0px;
width: 200px;
}
.footer {
background-color: brown;
height: 300px;
width: 100vw;
}
我想将我的 div 固定在底部,直到页脚开始显示,然后让它在页脚顶部滚动。我应该使用粘性定位吗?如果是这样,我该怎么做?如果没有,是否有更好的解决方案? 谢谢
您可以使用 position: sticky
和 bottom: 0
将其粘贴到视口底部(回答您的 如何 的问题)。由于它的非粘性位置就在页脚之前,当视口到达那里时它会自然地停留。
body {
font-weight: bold;
font-size: 24px;
padding-bottom: 300px;
}
main * {
padding: 10px;
background-color: #ccc;
border: 1px solid #000;
}
.content {
min-height: 1000px;
}
.sticky {
position: sticky;
/* the important part - stick to the bottom */
bottom: 0;
border: 1px solid red;
background-color: white;
}
<main>
<div class="content">content</div>
<div class="sticky">I'm sticky</div>
<footer>footer</footer>
</main>
话虽这么说,正如 Will 在评论中提到的那样 - 你应该使用它吗?这取决于您支持的浏览器。如果您需要支持旧版浏览器,则需要后备 and/or JavaScript 来处理定位。