我试图在主页组件的末尾放置一个页脚。在我的网站中,溢出仅针对具有媒体查询的移动视图自动设置,因此滚动对于桌面视图保持隐藏。我已经使用了我能找到的所有解决方案,但没有任何帮助,页脚在底部的桌面视图中完美对齐,但对于移动视图,它在屏幕末端(而不是页面)对齐。我不知道如何解决这个问题。
网站: https: //shivamaima.netlify.com/
git: https: //github.com/darwin619/portfolio
.homepage {
text-align: center;
width: 100%;
position:relative;
padding:0;
margin:0;
min-height:100vh;
top:0;
@media screen and (max-width: 600px) {
overflow: auto;
height: 100vh;
}
.footer {
position: absolute;
right: 0;
bottom: 0;
left: 0;
padding: 1rem;
text-align: center;
}
Run Code Online (Sandbox Code Playgroud)
这里有几个解决方案。而不是bottom: 0使用:
margin-top: 100vh;
Run Code Online (Sandbox Code Playgroud)
这会将页脚设置在视口高度的底部。
然而,你的页面有很多布局问题,这确实是一个创可贴。您应该考虑使用flexbox、、min-height或grid创建粘性页脚。
话虽如此,使用 React 的解决方案在大多数情况下都是如此。
以下解决方案更可取,因为它们是“真正的”动态粘性页脚。这意味着,页脚停留在底部,直到主要内容超出该区域,此时页脚将开始向下调整其位置:
margin-top: 100vh;
Run Code Online (Sandbox Code Playgroud)
nav {
height: 40px;
padding: 10px;
background: lightblue;
}
main {
padding: 20px;
background: purple;
min-height: calc(100vh - 170px);
}
footer {
background: magenta;
padding: 10px;
height: 50px;
}Run Code Online (Sandbox Code Playgroud)
可以看出,我们将内容的最小高度100vh设置为减去容器的组合高度(加上填充nav)content。
这会导致页脚粘住,并且如果内容超过该min-height值,页脚还可以进一步下降。
使用 可以实现相同的效果flexbox,这可以说是一个更动态的解决方案。然而,它是以额外的容器元素为代价的。我们可以应用flex,body但这很少是一个合适的解决方案:
<html>
<body>
<nav>
Navigation
</nav>
<main>
Page content
</main>
<footer>
Footer that stays put
</footer>
</body>
</html>Run Code Online (Sandbox Code Playgroud)
.container {
display: flex;
min-height: calc(100vh - 40px);
flex-direction: column;
}
nav {
height: 40px;
padding: 10px;
background: lightblue;
}
main {
padding: 20px;
background: purple;
flex: 1;
}
footer {
background: magenta;
padding: 10px;
height: 50px;
}Run Code Online (Sandbox Code Playgroud)
<body>
// Use className instead of class for react (jsx)
<div class="container">
<nav>
Navigation
</nav>
<main>
Main Content Area
</main>
<footer>
Footer that stays put
</footer>
</div>
</body>Run Code Online (Sandbox Code Playgroud)
.container {
display: grid;
grid-gap: 1em 0;
grid: auto auto 1fr / 10vw 1fr 10vw;
margin: 0;
min-height: calc(100vh - 40px);
}
nav {
background-color: lightblue;
grid-column: 2;
padding: 20px;
}
main {
background-color: purple;
display: grid;
grid-column: 2;
padding: 20px;
}
footer {
background-color: magenta;
align-self: end;
grid-column: 2;
padding: 20px;
}Run Code Online (Sandbox Code Playgroud)
注意:如果您正在处理 React 项目,请更改class为。className