我正在尝试将一个页面分成 3 个部分。页眉、正文和页脚。我找到了 this接近我需要的博客文章。但是,当您向上或向下滚动时,采用他的方法的页眉和页脚会粘在窗口上。
此外,我想要在 body 部分内添加一个额外的 div
,它水平和垂直居中,固定宽度为 600px。并且高度应该是自动的但不与页眉或页脚重叠。因此,这两个部分之间也应该有一个填充。
我用了his居中部分的方法效果很好。但我也在使用 Twitter Bootstrap 3
。而且我从来没有得到我想要的结果。
有人能帮我至少了解一下在没有 TB3
的情况下也能正常工作的基础知识吗?
提前致谢!
[编辑] 总而言之,我想要的是:
- 页面分为 3 个部分,页脚和页眉不粘在窗口上;
- 将
div
置于正文部分的中央,宽度固定,高度不断增加,且不应与页眉或页脚重叠;
[编辑 2] 抱歉,我忘了说页眉和页脚的高度固定为 65px。
最佳答案
不知道里面有多高div
的高度将是,并且高度将是可变的,因此很难创建一个一刀切的解决方案,尤其是考虑到不同的设备和计算机具有不同的屏幕尺寸和分辨率。除了这个问题之外,您的页眉和页脚也可能具有可变高度,因此这也会使事情复杂化。
为了解决这些怪癖,更好地控制您的变化 div
高度和它在页面上的位置,我会考虑使用 JavaScript 来控制它的位置。这样,您就可以监控它的高度何时发生变化(取决于您打算做什么),并根据其当前高度动态移动它。
在下面的示例中,我使用 jQuery 来轻松完成 JavaScript。您可以从their site here下载,并将其包含在您的代码中。
这是一个基本示例(首先是 HTML):
<div id="header"></div>
<div id="container"></div>
<div id="footer"></div>
然后是一些 CSS:
html, body {
height: 100%;
min-height: 400px; /* to cater for no element 'collision'... */
margin: 0;
padding: 0;
position: relative; /* to keep header and footer positioned correctly... */
}
#header {
background-color: green;
height: 65px;
position: absolute;
top: 0;
left: 0;
width: 100%;
}
#container {
background-color: red;
width: 600px;
height: 40%;
position: absolute;
left: 50%;
margin-left: -300px; /* 50% over, then move back 300px to center... */
}
#footer {
background-color: orange;
height: 65px;
position: absolute;
bottom: 0;
left: 0;
width: 100%;
}
最后,您的 JavaScript。把这个放在 <head>...</head>
HTML 的一部分。我已尝试尽可能多地发表评论,但如果有任何不清楚的地方,请告诉我:
<script src="./path/to/jquery.js"></script>
<script>
// this will run this function as soon as the page is loaded...
$(function(){
// bind the resize event to the window...
// this will call the 'centerMyContent' function whenever the
// window is resized...
jQuery(window).bind('resize', centerMyContent);
// call the 'centerMyContent' function on the first page load...
centerMyContent();
});
// the actual centring function...
function centerMyContent(){
// get the body and container elements...
var container = jQuery('#container');
var body = jQuery('body');
// work out the top position for the container...
var top = (body.height() / 2) - (container.height() / 2);
// set the container's top position...
container.css('top', top + 'px');
}
</script>
我希望这能帮助您走上正轨!在 Chrome、Firefox 和 Internet Explorer 7、8、9 和 10 中成功测试。
关于html - 用CSS将页面分成3个部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19356854/