我花了几个小时试图解决这个问题,但没有任何结果。
我想要的很简单(理论上)。我想要一个全屏网页,其中页眉始终位于顶部,页脚始终位于底部。内容是动态的。如果它超出页面,它应该增长,将页脚向下推。 我想要在水平居中的内容中有一个 980 像素宽的 div。我想给那个 div 一个不同于背景颜色的颜色。如果内容只有一行文本,我仍然希望 div(背景色)成为页脚和页眉之间 100% 的空间。我做了一个有趣的例子:
我目前的代码:
<html>
<head>
<style>
#container {
height: 100%;
width: 100%;
background: green;
position: absolute;
}
#header, #footer {
height: 100px;
width: 100%;
background: red;
}
#body {
height: 100%;
width: 100%;
background: blue;
}
#content {
width: 980px;
background: yellow;
}
</style>
<head>
<body>
<div id="container">
<div id="header"></div>
<div id="body">
<div id="content">
content
</div>
</div>
<div id="footer"></div>
</div>
</body>
</html>
这段代码远非正常。首先,如果内容超出页面,它不能将页脚保留在页面底部。其次,我不知道如何包含 980px 居中的 div。
最佳答案
要使内容居中,请使用 margin: 0 auto;
。这会将顶部和底部的边距设置为 0,并自动调整左侧和右侧的边距。您所问的很可能必须涉及 JavaScript。您将始终有一个固定的页脚,或者将页脚放在内容的底部。
你问的不是很实用。如果你有很多内容,你的页脚无论如何都会被压低。当页面上的内容很少时,听起来您希望将页脚放在底部。
我已经编写了一些代码来帮助您入门。 JavaScript
提供了您想要的效果。取消注释CSS高度或在div中添加大量内容,页脚将被下推。
<html>
<head>
<style>
body, #body, #header, #footer { width: 100%;margin: 0; padding: 0; }
#header { height: 100px; background: #7eff02; }
#footer { height: 100px; background: #ff5c01; }
#content { width: 980px; background: #fcff00; margin: 0 auto;
/*height: 3000px;*/
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script>
$(document).ready(function () {
var headerHeight = $("#header").height();
var footerHeight = $("#footer").height();
var resizeTimer;
$(window).resize(function () {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(onWindowResize(), 100);
});
onWindowResize();
function onWindowResize() {
if ($("#content").height() < (window.innerHeight - headerHeight - footerHeight)) {
$("#content").css("height", (window.innerHeight - headerHeight - footerHeight));
$("#footer").css({ "position": "fixed", "bottom": "0" });
}
else {
$("#content").css("height", "");
$("#footer").css({ "position": "", "bottom": "" });
}
}
});
</script>
<head>
<body>
<div id="container">
<div id="header"></div>
<div id="body">
<div id="content">
CONTENT
</div>
</div>
<div id="footer"></div>
</div>
</body>
</html>
关于html - 使用 css 固定页脚和页眉以及动态内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19747908/